将数据帧列表合并为一个保留行名 [英] Combine a list of data frames into one preserving row names

查看:69
本文介绍了将数据帧列表合并为一个保留行名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实了解将数据帧列表合并为一个的基本知识,如

I do know about the basics of combining a list of data frames into one as has been answered before. However, I am interested in smart ways to maintain row names. Suppose I have a list of data frames that are fairly equal and I keep them in a named list.

library(plyr)
library(dplyr)
library(data.table)

a = data.frame(x=1:3, row.names = letters[1:3])
b = data.frame(x=4:6, row.names = letters[4:6])
c = data.frame(x=7:9, row.names = letters[7:9])

l = list(A=a, B=b, C=c)

当我使用do.call时,列表名称与行名称结合在一起:

When I use do.call, the list names are combined with the row names:

> rownames(do.call("rbind", l))
[1] "A.a" "A.b" "A.c" "B.d" "B.e" "B.f" "C.g" "C.h" "C.i"

当我使用rbind.fillbind_rowsrbindlist中的任何一个时,行名将替换为数字范围:

When I use any of rbind.fill, bind_rows or rbindlist the row names are replaced by a numeric range:

> rownames(rbind.fill(l))
> rownames(bind_rows(l))
> rownames(rbindlist(l))
[1] "1" "2" "3" "4" "5" "6" "7" "8" "9"

当我从列表中删除名称时,do.call会产生所需的输出:

When I remove the names from the list, do.call produces the desired output:

> names(l) = NULL
> rownames(do.call("rbind", l))
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i"

那么我缺少一个可以对行名提供更好控制的函数吗?我确实需要在其他上下文中使用这些名称,因此删除它们不是最佳选择.

So is there a function that I'm missing that provides some finer control over the row names? I do need the names for a different context so removing them is sub-optimal.

推荐答案

要保留行名,您只需执行以下操作:

To preserve rownames, you can simply do:

do.call(rbind, unname(l))

#  x
#a 1
#b 2
#c 3
#d 4
#e 5
#f 6
#g 7
#h 8
#i 9

或者如您通过将l的行名设置为NULL所强调的那样,也可以通过以下方式完成:

Or as you underlined by setting the rownames of l to NULL , this can be also done by:

do.call(rbind, setNames(l, NULL))

这篇关于将数据帧列表合并为一个保留行名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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