Looping over lists, extracting certain elements and delete the list?

Solution 1:

Here’s a possible solution using a function to rename the object you’re loading in. I got loadRData from here. The loadRData function makes this a bit more approachable because you can load in the object with a different name.

Create some data for a reproducible example.

tab2000_agg <- 
  list(
    A = 1:5,
    b = 6:10
  )
tab2001_agg <- 
  list(
    A = 1:5,
    d = 6:10
  )

save(tab2000_agg, file = "2000_agg.rda")
save(tab2001_agg, file = "2001_agg.rda")
rm(tab2000_agg, tab2001_agg)

Using your loop idea.

loadRData <- function(fileName){
    load(fileName)
    get(ls()[ls() != "fileName"])
}

y <- list()
for(i in 2000:2001){
  objects <- paste("", i, "_agg.rda", sep="")
  data_list <- loadRData(objects)
  tmp <- data_list[["A"]]
  y[[i]] <- tmp
  rm(data_list)
}
y <- do.call(rbind, y)

You could also turn it into a function rather than use a loop.

getElement <- function(year){
  objects <- paste0("", year, "_agg.rda")
  data_list <- loadRData(objects)
  tmp <- data_list[["A"]]
  return(tmp)
}
y <- lapply(2000:2001, getElement)
y <- do.call(rbind, y)

Created on 2022-01-14 by the reprex package (v2.0.1)