Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Load and change variable names

I have 5 R objects with different names to load, each one contains a list with the same name. Is there any way that I can load them and change the list name at the same time? (Or other ways more efficient than what I do below?)

R objects name: A, B, C, D, E

List in the R object name: result

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

List names to change to: A_result, B_result, C_result, D_result, E_result

How I do it now:

load_name <- c('A','B','C','D','E')

for (i in 1:5){
    load (paste0 ('Output/Compiled_Models/',load_name[[i]]))
  }

A_result <- A
B_result <- B
C_result <- C
D_result <- D
E_result <- E

rm (list = A)
rm (list = B)
rm (list = C)
rm (list = D)
rm (list = E)

>Solution :

It is not entirely clear what object you work with. Indeed, it is preferable to work with RDS instead of .RData. You are using save and load, so I’ve written a small reproducible example to get you going.

A <- lm(mpg ~ ., data = mtcars)
B <- lm(disp ~ ., data = mtcars)

save(A, file = "A.RData")
save(B, file = "B.RData")


load_name <- c('A','B')
read_name <- paste0("read_", load_name)

for (i in seq_along(load_name)){
  x <- load(paste0 (load_name[i], ".RData"))
  assign(read_name[i], get(x))
  rm(list = x, envir = .GlobalEnv)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading