[英]How do i dynamically add column in dataframe if list of variable increases
How to add column dynamically in dataframe if list of variable increases. 如果变量列表增加,如何在数据框中动态添加列。 My dataframe:
我的数据框:
ID Value
1 list(F="20",B="rt")
2 list(F="20",B="rt",`H'="ty")
3 list(F="20",B="rt")
4 list(F="20")
Desired output: 所需的输出:
ID Value F B H
1 list(F="20",B="rt") 20 rt NA
2 list(F="20",B="rt",H="ty") 20 rt ty
3 list(F="20",B="rt") 20 rt NA
4 list(F="20") 20 NA NA
structure(list(Billing = list(NULL, structure
(list(`EUcust#` = "3",`Cust#` = "5", Com = "I", `Com#` = "6", Add = "Y"), .Names
= c("EUcust#",
"Cust#", "Com", "Com#", "Add"), class
= "data.frame", row.names = 1L))), .Names
= "Billing",
row.names = 8:9, class = "data.frame")
We can use tidyverse
我们可以使用
tidyverse
library(tidyverse)
df1 %>%
bind_cols(., map_df(.$Value, ~do.call(cbind.data.frame, .)))
# ID Value F B H
#1 1 20, rt 20 rt <NA>
#2 2 20, rt, ty 20 rt ty
#3 3 20, rt 20 rt <NA>
#4 4 20 20 <NA> <NA>
df1 <- structure(list(ID = 1:4, Value = structure(list(structure(list(
F = "20", B = "rt"), .Names = c("F", "B")), structure(list(
F = "20", B = "rt", H = "ty"), .Names = c("F", "B", "H")),
structure(list(F = "20", B = "rt"), .Names = c("F", "B")),
structure(list(F = "20"), .Names = "F")), class = "AsIs")),
.Names = c("ID",
"Value"), row.names = c(NA, -4L), class = "data.frame")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.