I am using World Input-Output Data for multiple years (2000 - 2014) and try to load them into a large dataframe. Each file with the is called "WIOTyear_October16_ROW.RData" with "year" being the number for that specific year.
First, i created a list of files and loaded them in the Global environment.
WIOD_list <- list.files(pattern = "*.RData")
lapply(WIOD_list,load,.GlobalEnv)
Afterwards i wanted to use rbind to merch them all together. The problem I am facing is that each loaded data frame is called "wiot", no matter of the year, so in the lapply, each dataframe will be overwritten by the next one. In the end, i only have one data frame for the year 2014 called "wiot".
Is there a way of renaming each loaded dataset to wiot_year before applying the next one?
CodePudding user response:
Would it help to put the lapply in a dataframe?
merged <- lapply(WIOD_list,load,.GlobalEnv)
CodePudding user response:
Within function f
create a new.env
ironment load
it there and get
it in a list
. Finally lapply
over it and rbind
.
f <- \(x) {
fenv <- new.env()
load(x, envir=fenv)
get(ls(fenv), envir=fenv)
}
do.call(rbind, lapply(list.files(pattern="*.RData"), f))
# X1 X2 X3 X4
# 1 1 4 7 10
# 2 2 5 8 11
# 3 3 6 9 12
# 4 1000 4000 7000 10000
# 5 2000 5000 8000 11000
# 6 3000 6000 9000 12000
Note: For the future you should consider using saveRDS
instead of save
, which allows to assign the read data to an object. (You can only use it to save a single object, though).
Data:
dat <- data.frame(matrix(1:12, 3, 4))
save(dat, file='test1.RData')
dat <- data.frame(matrix(1:12, 3, 4))*1000
save(dat, file='test2.RData')
rm(dat)