R by Rownames中的数据帧联合

时间:2013-05-06 22:19:13

标签: r dataframe union

我有4个数据帧,每个数据帧都是列表中的索引。我想将它们完全合并为一个数据帧。在数学的集合语言中,最有意义的是成为rownames上的联合。所以我可能会有这样的事情:

U <- union(dfSub[[1]], dfSub[[2]], dfSub[[3]], dfSub[[4]])

union函数的问题在于它仅对向量进行操作。我怎样才能让它在数据帧上工作?

  1. 如何将其翻译成R?
  2. 有没有更好的方法来达到预期的效果?
  3. 编辑:如何在联盟之后保留rownames?

2 个答案:

答案 0 :(得分:14)

首先,将它们绑定在一起:

df.cat <- rbind(dfSub[[1]], dfSub[[2]], dfSub[[3]], dfSub[[4]])

或更好:

df.cat <- do.call(rbind, dfSub[1:4])

第一步要求所有data.frames具有相同的列名。如果不是这样,那么您可能会对rbind.fill包中的plyr函数感兴趣:

library(plyr)
df.cat <- rbind.fill(dfSub[1:4])

然后,如果需要(作为集合联合),删除重复项:

df.union <- unique(df.cat)

答案 1 :(得分:-2)

您可以将数据框与merge功能结合使用。由于您有多个数据框,因此可以使用Reduce一次合并它们。

merged.data <- Reduce(function(...) merge(...), list(dfSub[[1]], dfSub[[2]], dfSub[[3]], dfSub[[4]])

举个例子:

> people <- c('Bob', 'Jane', 'Pat')
> height <- c(72, 64, 68)
> weight <- c(220, 130, 150)
> age <- c(45, 32, 35)
> height.data <- data.frame(people, height)
> weight.data <- data.frame(people, weight)
> age.data <- data.frame(people, age)

> height.data
  people height
1    Bob     72
2   Jane     64
3    Pat     68
> weight.data
  people weight
1    Bob    220
2   Jane    130
3    Pat    150
> age.data
  people age
1    Bob  45
2   Jane  32
3    Pat  35


> Reduce(function(...) merge(...), list(height.data, weight.data, age.data))
  people height weight age
1    Bob     72    220  45
2   Jane     64    130  32
3    Pat     68    150  35