Reputation: 355
I have a list of .rda (RData) files. I would like to quickly load this data into R, without having to call the load
function multiple times. I thought of using the load()
function with sapply
. However, using the following code, does not load any R objects in the workspace:
# List files
gewataPath <- list.files(path = file.path(datdir), pattern = glob2rx('Gewata*.rda'), full.names = T)
# Load files
sapply(gewataPath, function(file) {load(file)})
Neither does it give any error.
Running a loop does load the .rda files into the R workspace as RasterLayer objects:
for (i in 1:length(gewataPath)) {
load(gewataPath[i])
}
My question is: Why can't I use an apply()
function to quickly load .rda files into the R workspace, and do I have to use a loop?
About the data: The data contains RasterLayers (from the Landsat satellite), located in Gewata, Ethiopia.
Upvotes: 2
Views: 572
Reputation: 206606
load()
will load the data into the environment in which it was called. When you create function to pass to sapply
, that function gets it's own environment. If you want the objects to exist after the sapply
, you want to load the objects into the global environment, not the function environment. You can do that with the envir=
parameter
sapply(gewataPath, function(file) {load(file, envir=globalenv())})
Or just
sapply(gewataPath, load, envir=globalenv())
Upvotes: 6