rbind两个data.frame保留行顺序和行名 [英] rbind two data.frame preserving row order and row names

查看:221
本文介绍了rbind两个data.frame保留行顺序和行名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 data.frame 对象的列表,我想将行附加到彼此,即 merge(...,all = T)。但是, merge 似乎删除了我需要保持原样的行名称。有任何想法吗?示例:

I have a list of data.frame objects which i would like to row append to one another, ie merge(..., all=T). However, merge seems to remove the row names which I need to be kept intact. Any ideas? Example:

x = data.frame(a=1:2, b=2:3, c=3:4, d=4:5, row.names=c("row_1", "another_row1"))
y = data.frame(a=c(10,20), b=c(20,30), c=c(30,40), row.names=c("row_2", "another_row2"))
> merge(x, y, all=T, sort=F)
     a  b  c  d
  1  1  2  3  4
  2  2  3  4  5
  3 10 20 30 NA
  4 20 30 40 NA


推荐答案

既然你知道你实际上不是合并,但只是rbinding,也许这样的事情可以工作。它使用plyr中的 rbind.fill 。要使用它,请指定要$ rbind data.frame 列表 / code>。

Since you know you are not actually merging, but just rbind-ing, maybe something like this will work. It makes use of rbind.fill from "plyr". To use it, specify a list of the data.frames you want to rbind.

RBIND <- function(datalist) {
  require(plyr)
  temp <- rbind.fill(datalist)
  rownames(temp) <- unlist(lapply(datalist, row.names))
  temp
}
RBIND(list(x, y))
#               a  b  c  d
# row_1         1  2  3  4
# another_row1  2  3  4  5
# row_2        10 20 30 NA
# another_row2 20 30 40 NA

这篇关于rbind两个data.frame保留行顺序和行名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆