Home > Enterprise >  Saving data frames using a for loop with file names corresponding to data frames
Saving data frames using a for loop with file names corresponding to data frames

Time:07-28

I have a few data frames (colors, sets, inventory) and I want to save each of them into a folder that I have set as my wd. I want to do this using a for loop, but I am not sure how to write the file argument such that R understands that it should use the elements of the vector as the file names.

I might write:

DFs <- c("colors", "sets", "inventory")
for (x in 1:length(DFs)){
  save(x, file = "x.Rda")
  }

The goal would be that the files would save as colors.Rda, sets.Rda, etc. However, the last element to run through the loop simply saves as x.Rda.

In short, perhaps my question is: how do you tell R that I am wanting to use elements being run through a loop within an argument when that argument requires a character string?

For bonus points, I am sure I will encounter the same problem if I want to load a series of files from that folder in the future. Rather than loading each one individually, I'd also like to write a for loop. To load these a few minutes ago, I used the incredibly clunky code:

sets_file <- "~/Documents/ME teaching/R notes/datasets/sets.csv"
sets <- read.csv(sets_file)

inventories_file <- "~/Documents/ME teaching/R notes/datasets/inventories.csv"
inventories <- read.csv(inventories_file)

colors_file <- "~/Documents/ME teaching/R notes/datasets/colors.csv"
colors <- read.csv(colors_file)

CodePudding user response:

For compactness I use lapply instead of a for loop here, but the idea is the same:

lapply(DFs, \(x) save(list=x, file=paste0(x, ".Rda"))))

Note that you need to generate the varying file names by providing x as a variable and not as a character (as part of the file name).

To load those files, you can simply do:

lapply(paste0(DFs, ".Rda"), load, envir = globalenv())

CodePudding user response:

To save you can do this:

DFs <- list(color, sets, inventory)
names(DFs) = c("color", "sets", "inventory")
for (x in 1:length(DFs)){
  dx = paste(names(DFs)[[x]], "Rda", sep = ".")
  dfx = DFs[[x]]
  save(dfx, file = dx)
}

To specify the path just inform in the construction of the dx object as following to read.

To read:

DFs <- c("colors", "sets", "inventory")
# or
DFs = dir("~/Documents/ME teaching/R notes/datasets/")
for(x in 1:length(DFs)){
  arq = paste("~/Documents/ME teaching/R notes/datasets/", DFs[x], ".csv", sep = "")
  DFs[x] = read.csv(arq)
}

It will read as a list, so you can access using [[]] indexation.

  • Related