问题
Is there a neat way to convert a nested data.frame to a hierarchical list?
I do it below with a for loop, but ideally there is a neater solution that generalizes to an arbitrary number of nested columns.
nested_df <- expand.grid(V1 = c('a','b','c'),
V2 = c('z','y'))%>%
group_by_all()%>%
do(x=runif(10))%>%
ungroup
nested_ls <- list()
for(v1 in unique(nested_df$V1)){
for(v2 in unique(nested_df$V2)){
nested_ls[[v1]][[v2]] <- nested_df%>%
filter(V1==v1 & V2==v2)%>%
pull(x)%>%
unlist
}
}
str(nested_ls)
回答1:
If you are not very strict with the names z
and y
, and can also work with [[1]]
and [[2]]
, then you can directly do,
split(nested_df$x, nested_df$V1)
If you need the names, then
lapply(split(nested_df, nested_df$V1), function(i)split(i$x, i$V2))
#Or as @Frank mentions in comments, we can use setNames
lapply(split(nested_df, nested_df$V1), function(i) setNames(i$x, i$V2))
来源:https://stackoverflow.com/questions/55264739/convert-nested-data-frame-to-a-hierarchical-list