I have a simple function to create a list of raster files from a list with their names (in .grd format, and called list_names in the example below):
ListRasters <- function(list_names) {
raster_list <- list() # initialise the list of rasters
for (i in 1:(length(list_names))){
grd_name <- list_names[i] # list_names contains all the names of the images in .grd format
raster_file <- raster(grd_name)
}
raster_list <- append(raster_list, raster_file) # update raster_list at each iteration
}
# Apply the function
raster_list <-lapply(list_names, FUN = ListRasters)
The desired result should be in the format:
[[1]]
class : RasterLayer
# etc
[[2]]
class : RasterLayer
# etc
But instead I get them in the format:
[[1]]
[[1]][[1]]
class : RasterLayer
# etc
[[2]]
[[2]][[1]]
class : RasterLayer
# etc
That is a problem because later on I can not access the items on the raster list. I can't find a solution because I don't understand why the iteration gives this format of result. Can you give me some explanation or some advice on how to fix the function, or can you see where I am making a mistake?
Any help is more than welcome!
Thankyou!!
It seems that something is odd with your loop. Nevertheless, the
lapply
is going to return a list, maybe you should trysapply
.I think this should give you what you want.
EDIT:
It would be better if you had put a minimal reproducible example, for we do not know how the data is and what is the
raster
function, but below follows a toy example with the differences of output oflapply
andsapply
.PS: and it does seem that your formula iteration is not correct, but you would have to provide more information so we can fix the formula.
Using
lapply
:The output is:
Using
sapply
:The output is: