dat <- list(list(structure(list(ID = 1, Gender = structure(1L, .Label = "Male", class = "factor"),
Phrase = structure(1L, .Label = "Hello", class = "factor"),
Phrase2 = structure(1L, .Label = "Goodbye", class = "factor")), .Names = c("ID",
"Gender", "Phrase", "Phrase2"), row.names = c(NA, -1L), class = "data.frame"),
structure(list(ID = 1, Gender = structure(1L, .Label = "Female", class = "factor"),
Phrase = structure(1L, .Label = "Good afternoon", class = "factor"),
Phrase2 = structure(1L, .Label = "Goodbye", class = "factor")), .Names = c("ID",
"Gender", "Phrase", "Phrase2"), row.names = c(NA, -1L), class = "data.frame")),
list(structure(list(ID = 2, Gender = structure(1L, .Label = "Male", class = "factor"),
Phrase = structure(1L, .Label = "Hello", class = "factor"),
Phrase2 = structure(1L, .Label = "Good afternoon", class = "factor")), .Names = c("ID",
"Gender", "Phrase", "Phrase2"), row.names = c(NA, -1L), class = "data.frame"),
structure(list(ID = 2, Gender = structure(1L, .Label = "Female", class = "factor"),
Phrase = structure(1L, .Label = "Goodbye", class = "factor"),
Phrase2 = structure(1L, .Label = "Goodbye", class = "factor")), .Names = c("ID",
"Gender", "Phrase", "Phrase2"), row.names = c(NA, -1L
), class = "data.frame")))
> dat
[[1]]
[[1]][[1]]
ID Gender Phrase Phrase2
1 1 Male Hello Goodbye
[[1]][[2]]
ID Gender Phrase Phrase2
1 1 Female Good afternoon Goodbye
[[2]]
[[2]][[1]]
ID Gender Phrase Phrase2
1 2 Male Hello Good afternoon
[[2]][[2]]
ID Gender Phrase Phrase2
1 2 Female Goodbye Goodbye
我有一个名为dat
的data.frames列表,其中每个列表元素中有多个条目(例如,按性别划分)。如何将这个data.frames列表组合成一个看起来像这样的data.frame?
ID Gender Phrase Phrase2
1 1 Male Hello Goodbye
2 1 Female Good afternoon Goodbye
3 2 Male Hello Good afternoon
4 2 Female Goodbye Goodbye
我已尝试ldply(dat, data.frame)
,do.call("rbind", dat)
和rbind.fill(dat)
无济于事。
答案 0 :(得分:3)
我们可以尝试
library(tidyverse)
map_df(dat, bind_rows)
# ID Gender Phrase Phrase2
#1 1 Male Hello Goodbye
#2 1 Female Good afternoon Goodbye
#3 2 Male Hello Good afternoon
#4 2 Female Goodbye Goodbye
答案 1 :(得分:1)
使用tidyverse包的另一种方式。
library(tidyverse)
dat %>% flatten() %>% bind_rows()
# ID Gender Phrase Phrase2
# 1 1 Male Hello Goodbye
# 2 1 Female Good afternoon Goodbye
# 3 2 Male Hello Good afternoon
# 4 2 Female Goodbye Goodbye