Home > database >  Load and change variable names
Load and change variable names

Time:01-16

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

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)

CodePudding user response:

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)
}
  •  Tags:  
  • Related