I have a list of lists called step2
containing dataframes like this one:
And I want to extract every element in the list as a single dataframe, so that I have one dataframe called Likert_rank_Americas
, Likert_rank_APAC
, Likert_rank_Civil_law
and so on for each dataframe contained in the list.
I tried with this:
list2env(step2,envir=.GlobalEnv)
But I only get the sub-lists contained in the main one as single objects, like so:
While what I want instead are the underlying dataframes as standalone objects, with the names as specified above. Is it possible to do this in a neat way without using list2env
for each sub-list and then manually renaming each dataset?
I am quite new to R so apologies if the solution's easy.
Thanks in advance!
CodePudding user response:
Without any data provided by you, what you want specifically is hard to guess, but at a minimum, to access a list of dataframes you need to follow this kind of logic...
a.1 <- data.frame(matrix(1:9, nrow=3))
a.2 <- data.frame(matrix(6:14, nrow=3))
data <- list(list(a.1,a.2),list("1","2"))
# NOTE: want only info from data[1] processed
library(purrr)
b <- map_dfr(data[1],rbind)
b
class(b)
dim(b)
# > b
# X1 X2 X3
# 1 1 4 7
# 2 2 5 8
# 3 3 6 9
# 4 6 9 12
# 5 7 10 13
# 6 8 11 14
# > class(b)
# [1] "data.frame"
# > dim(b)
# [1] 6 3
CodePudding user response:
I think this oneliner should work. The function 'list2env' assigns all list components to the global environment. The function 'lapply' applies the function 'list2env' to every element of the list 'step2'.
step2%>% lapply(.%>% {list2env(., envir=.GlobalEnv)})
You can rename the dataframes before doing so of course.
names(step2$Geography)<- c(
'Likert_Rank_Americas',
'Likert_Rank_APAC',
'Likert_Rank_EMEA',
'Likert_Rank_Global')
names(step2$Legal_System)<- c(
'Likert_Rank_Civil_law',
'Likert_Rank_Common_law')
CodePudding user response:
I created a quick reproducible dataset for testing with (this is good practice to include when asking for help)
dat <- list(list(data.frame(), data.frame(), data.frame()), list(data.frame(), data.frame(), data.frame()))
names(dat) <- c('list1' , 'list2')
names(dat$list1) <- c('A', 'B', 'C')
names(dat$list2) <- c('D', 'E', 'F')
Then I used
lapply(dat, list2env, .GlobalEnv)
Edit: To rename the dataframes, use the same structure as above where I named the sample dataframe, but use the names you want the end objects to have. If you want to automate this process, I would seperate it into a different question, but I suspect you would be able to find another post with the answer already.
Something like (pseudo-code)...
name_vec <- paste0('naming_convention_', names(step2$Geography))
names(step2$Geography) <- name_vec