以树格式R存储数据

时间:2013-03-27 17:36:05

标签: r

我想在r中以树格式存储数据。 R中是否有可以使用的包? 数据样本:

lat lon ,v1,v2,v3,parent,id
23.9917345,90.4195876,83,3,0,0,1

此处父列表示当前行的父ID

1 个答案:

答案 0 :(得分:3)

您可以使用aggregate(id, by=list(parent=parent), paste, collapse=" ")

找到没有循环的孩子

示例:

> n <- 30; d <- data.frame(parent=sample(n,n,TRUE), id=1:n, value=runif(n))
> children <- with(d, aggregate(id, by=list(parent=parent), paste, collapse=" "))
> children
   parent        x
1       2       24
2       3 12 20 28
3       4        5
4       7  8 17 18
5       8       29

(剪断)

现在您可以将原始数据集中的内容与此合并:

> names(children) <- c("id", "children")
> merge(d, children, all.x=TRUE)
   id parent       value children
1   1     13 0.319805784     <NA>
2   2     24 0.847229065       24
3   3     21 0.946230816 12 20 28
4   4     12 0.915684833        5
5   5      4 0.754628841     <NA>

(剪断)

相关问题