Home > other >  In R: list of dataframes, automatically extract all dfs separately
In R: list of dataframes, automatically extract all dfs separately

Time:06-06

I have a list, where each element is a dataframe, is there some option with which I could automatically extract all the dataframes with automatically generated names?

for example: (I first have to artifically create a list here)

d1 <- data.frame(x1 = c(1, 2, 3),
             y1 = c(4, 5, 6))
d2 <- data.frame(x2 = c(4, 5, 6),
             y2 = c(7, 8, 9))

mylist <- list()
mylist[[1]] <- d1
mylist[[2]] <- d2

is there some loop I could write that would extract all the elements of the list together as separate dataframe and save them in the environment?

I thought about something like

names <- paste0("mydata", 1:length(mylist))  #names of the dataframes
for (i in 1:length(mylist)){
names[i] <- data.frame() #initialization
names[i] <- mylist[[i]]
}

and then all dataframes should generated into the environment, but unfortunately this does not work, the problem is in the initialization step. it can not create empty dataframes with the names[i]. Would be thankful if someone could tell me how to redo this

CodePudding user response:

Objects may be created in the global env with list2env on a named list - setNames sets the names of the list (it is a bad practise to create multiple objects in the global env i.e. instead keep it in the list itself)

list2env(setNames(mylist, names), .GlobalEnv)

Regarding the OP's code, to create objects in for loop, use assign and not names<-

for (i in seq_along(mylist))
    {
     assign(names[i], mylist[[i]])
    }
  • Related