I'm struggling with this problem:
I have three lists of dataframes (each list has the same number of rows, each dataframe has 3 columns). I want to combine the lists into one nested dataframe, such that there are 3 columns (one column for a list).
Sample code:
a_list_of_dfs <- lapply(seq_along(a_list), function(i) {
tibble(x = a_list[[i]]$x,
y = a_list[[i]]$y,
z = a_list[[i]]$z)
})
b_list_of_dfs <- lapply(seq_along(b_list), function(i) {
tibble(x = b_list[[i]]$x,
y = b_list[[i]]$y,
z = b_list[[i]]$z)
})
c_list_of_dfs <- lapply(seq_along(c_list), function(i) {
tibble(x = c_list[[i]]$x,
y = c_list[[i]]$y,
z = c_list[[i]]$z)
})
nested_df <- tibble(a=a_list_of_df,
b=b_list_of_df,
c=c_list_of_df)
The problem is, this solution doesn't give me the result I want. The idea is to be able to access the nested dataframe like this:
nested_df$a$x
How can I change that to get the result I want?
Edit:
a_list
, b_list
and c_list
are nested lists where each element has some string attributes. For example, a_list
has X rows and each row has attributes name
, label
and value
. So I want to achieve a solution where I can just access the nested dataframe like this:
nested_df$a$name # and value etc.
The result of the dput
function below (kept only the first two elements, the strcture is the same across a list):
`list(structure(list(name = "VS", label = "VS",
value = "SUM"), .Names = c("name",
"label", "value")), structure(list(name = "VP",
label = "VP", value = "SUM"), .Names = c("name",
"label", "value")),`
My solution
Passing a dataframe instead of a list of 1-row dataframes as a column worked for me.
The structure of your data is not very clear because your sample is a bit small. But does this do what you want?
library(tidyverse)
df <- list(structure(list(name = "VS", label = "VS", value = "SUM"),
.Names = c("name", "label", "value")),
structure(list(name = "VP", label = "VP", value = "SUM"),
.Names = c("name", "label", "value")))
df <- df %>% set_names(c("a", "b"))
df$a$name
df %>% as_tibble()
You should name the list elements.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.