我有一个data.frame,其中一列包含值列表:
d <- data.frame(id=1:2, parent=c("Jon", "Mark"))
d$children <- list(c("Mary", "James"), c("Greta", "Sally"))
如何将此data.frame转换为以下结构:
target_df <- data.frame(id=1:4, parent=c("Jon", "Jon","Mark", "Mark"), children = c("Mary", "James","Greta", "Sally"))
答案 0 :(得分:0)
您应该使用unnest
中的tidyr
,也可以映射tidyverse
,对不起,我已经映射了tidyverse
.Rprofile文件。无论如何
library(tidyverse) #or map library(tidyr) whatever suits you
d %>%
unnest(children) %>%
mutate(id = 1:row_number()) #You may not want to run this if you want to keep your original id
也以 base R 方式:
d_new <- do.call('rbind', do.call('Map', c(data.frame, d)))
再次,要重置ID,我们必须使用1:nrow(d)
d_new$id <- 1:nrow(d) #This may not be required if you don't want to reset your id
感谢所有评论,欢迎所有评论,是的,我不知所措。 感谢@Ronak Shah,@ r2evans