我有一个数据框列表,对于每个列表,我都有一个名称,它是USERID,以下是列表的示例:
$'AAAAAA'
AA BB CC
a b 1
c d 2
e f 3
S'BBBBBB'
AA BB CC
g h 1
i j 2
k l 3
我的问题是如何将此列表转换为一个数据框,其中有一个显示USERID的新列,如下例所示:
AA BB CC USERID
a b 1 AAAAAA
c d 2 AAAAAA
e f 3 AAAAAA
g h 1 BBBBBB
i j 2 BBBBBB
k l 3 BBBBBB
任何想法如何做到。非常感谢你提前
答案 0 :(得分:6)
由于cbind
将其参数再循环到最长向量的长度,您可以尝试
Reduce(rbind, Map(cbind, x, USERID = names(x)))
# AA BB CC USERID
# 1 a b 1 AAAAA
# 2 c d 2 AAAAA
# 3 e f 3 AAAAA
# 4 g h 1 BBBBB
# 5 i j 2 BBBBB
# 6 k l 3 BBBBB
其中x
是
structure(list(AAAAA = structure(list(AA = c("a", "c", "e"),
BB = c("b", "d", "f"), CC = 1:3), .Names = c("AA", "BB",
"CC"), class = "data.frame", row.names = c(NA, -3L)), BBBBB = structure(list(
AA = c("g", "i", "k"), BB = c("h", "j", "l"), CC = 1:3), .Names = c("AA",
"BB", "CC"), class = "data.frame", row.names = c(NA, -3L))), .Names = c("AAAAA",
"BBBBB"))
答案 1 :(得分:6)
另一种方法,使用tidyr
的开发版本:
# install.packages("devtools")
devtools::install_github("hadley/tidyr")
library(tidyr)
unnest(mylist, USERID)
# USERID AA BB CC
# 1 AAAAA a b 1
# 2 AAAAA c d 2
# 3 AAAAA e f 3
# 4 BBBBB g h 1
# 5 BBBBB i j 2
# 6 BBBBB k l 3
答案 2 :(得分:4)
或(如果l
是您的清单)
library(data.table)
rbindlist(Map(cbind, l, USERID = names(l)))
# AA BB CC USERID
# 1: a b 1 AAAAAA
# 2: c d 2 AAAAAA
# 3: e f 3 AAAAAA
# 4: g h 1 BBBBBB
# 5: i j 2 BBBBBB
# 6: k l 3 BBBBBB