How to iterate over a list preserving the format o

2019-05-22 17:41发布

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!!

1条回答
祖国的老花朵
2楼-- · 2019-05-22 18:25

It seems that something is odd with your loop. Nevertheless, the lapply is going to return a list, maybe you should try sapply.

raster_list <-sapply(list_names, FUN = ListRasters)

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 of lapply and sapply.

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.

list_names <- c("a", "b","c", "d") #defining the list_names

#defining the function
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 <- paste("file", grd_name, sep=".")
  }

  raster_list <- append(raster_list, raster_file) # update raster_list at each iteration
}

Using lapply:

raster_list <-lapply(list_names, FUN = ListRasters)

The output is:

  [[1]]
[[1]][[1]]
[1] "file.a"


[[2]]
[[2]][[1]]
[1] "file.b"


[[3]]
[[3]][[1]]
[1] "file.c"


[[4]]
[[4]][[1]]
[1] "file.d"

Using sapply:

raster_list <-sapply(list_names, FUN = ListRasters)

The output is:

$a
[1] "file.a"

$b
[1] "file.b"

$c
[1] "file.c"

$d
[1] "file.d"
查看更多
登录 后发表回答