Home > Software engineering >  save list of data frames in a loop
save list of data frames in a loop

Time:12-17

I have a list of data sets that I need to loop through and save the output. the names assigned belong to a character vector. For example:

list_data <- mtcars %>% group_split(cyl)

names_vector <- c("low", "medium", "high")

# this is what I am doing

low <- list_data[[1]]

medium <- list_data[[2]]

high <- list_data[[3]]

The names assigned belong to the character vector and it needs to be in order. the number of datasets in the list match the length of names_vector. but this needs to be iterated using a loop or some purr/dplyr functions.

Thanks

CodePudding user response:

No need to loop, you can rename the dataframes in a list using,

names(list_data) <- names_vector

Then separate each dataframes to environment,

list2env(list_data,envir=.GlobalEnv)

CodePudding user response:

This is a duplicate of many questions. You can use assign or utilize the %<-% from the Zealot package.

library(zeallot)
c(low, medium, high) %<-% list_data
# Alternative:
names(list_data) <- c("low", "medium", "high")
mapply(list_data, names(list_data), FUN = \(x, name)assign(name, x, envir = globalenv()))
  • Related