我有一个如下列表。
p1
$ColA
Var1 Freq
1 asgfg 2.1
2 dds 2.1
3 dfg 4.3
4 dfh 2.1
$ColB
Var1 Freq
1 A 44.7
2 B 55.3
我需要的东西如下所示。基本上,我想将它们组合成一个数据框。
df
Col Var1 Freq
ColA asgfg 2.1
ColA dds 2.1
ColA dfg 4.3
ColA dfh 2.1
ColB A 44.7
ColC B 55.3
答案 0 :(得分:3)
一个选项是bind_rows
library(dplyr)
bind_rows(p1, .id = 'Col')
# Col Var1 Freq
#1 ColA asgfg 2.1
#2 ColA dds 2.1
#3 ColA dfg 4.3
#4 ColA dfh 2.1
#5 ColB A 44.7
#6 ColB B 55.3
或与base R
out <- do.call(rbind, Map(cbind, Col = names(p1), p1))
row.names(out) <- NULL
p1 <- list(ColA = structure(list(Var1 = c("asgfg", "dds", "dfg", "dfh"
), Freq = c(2.1, 2.1, 4.3, 2.1)), class = "data.frame", row.names = c("1",
"2", "3", "4")), ColB = structure(list(Var1 = c("A", "B"), Freq = c(44.7,
55.3)), class = "data.frame", row.names = c("1", "2")))
答案 1 :(得分:0)
我们可以使用data.table
软件包:
data.table::rbindlist(p1, idcol = "col")
或使用purrr
:
purrr::map_df(p1, I, .id = "col")
获取:
# col Var1 Freq
# 1: ColA asgfg 2.1
# 2: ColA dds 2.1
# 3: ColA dfg 4.3
# 4: ColA dfh 2.1
# 5: ColB A 44.7
# 6: ColB B 55.3
中提供的数据