0

At the beginning of a script I am loading all available data.frames as follows (source):

temp = list.files(pattern="*.Rds")
for (i in 1:length(temp)) assign(temp[i], readRDS(temp[i]))

However, loaded data frames inherit the extension (i.e, .Rds). I would like to strip the .Rds from the data.frame names (for efficiency's sake, before they are created).

Here, I found that I could use the following code: stripExtension <- gsub('.Rds', "", temp). However, inserted between the 2 lines of code above, the data frames are not loaded because the extension is missing:

temp = list.files(pattern="*.Rds")
stripExtension <- gsub('.Rds', "", temp)
for (i in 1:length(stripExtension)) assign(stripExtension[i], readRDS(stripExtension[i]))

My question:

  • How can I load multiple .Rds files at once and give them another name than the file name it originated from (i.e., the .Rds filename, but without the .Rds extension)?

Any help highly appreciated.


System used:

  • R version: 4.1.1 (2021-08-10)
  • RStudio version: 1.4.1717
  • OS: macOS Catalina version 10.15.7
Phil
  • 7,287
  • 3
  • 36
  • 66
pdeli
  • 436
  • 3
  • 13

2 Answers2

1
temp = list.files(pattern="[.]Rds$")
obj_nms = tools::file_path_sans_ext(basename(temp))
for (i in seq_along(temp))
    assign(obj_nms[[i]], readRDS(temp[[i]]))

tools comes with r built in so you do not have to install it. basename removes the directory name from the file path.

Eyayaw
  • 1,033
  • 5
  • 10
0

What finally worked:

rdsFilesFolder <- path("rdsFiles")
listOfRdsFiles <- list.files(path = rdsFilesFolder, pattern="*.Rds")
stripExtensions <- gsub('.Rds', "", listOfRdsFiles)

for (numberOfRdsFiles in 1:length(stripExtensions)) {
  assign(stripExtensions[numberOfRdsFiles], 
         readRDS(paste0("./", rdsFilesFolder, "/", listOfRdsFiles[numberOfRdsFiles])))}

The for loop has an assign argument that can be different from the readRDS argument.

This code has the added advantage to recognise filenames that start with % (e.g., %5EGSPC.Rds).

pdeli
  • 436
  • 3
  • 13
  • There is a function that does stripping extensions from paths: `tools::file_path_sans_ext`. – Eyayaw Sep 04 '21 at 18:10