1

Suppose I have this list of rasters:

(L <- setNames(replicate(3, raster(matrix(runif(100), 10))), c('A', 'B', 'C')))

How can I unlist a list of rasters to individual objects in R?

With a list of dataframes, I can use something similar to the following code:

df <- data.frame(matrix(unlist(l), nrow=132, byrow=T),stringsAsFactors=FALSE)

1 Answer 1

1

Not entirely clear what you are after here. If you would like a single raster class object containing all of the rasters, this would be quite different than creating individual raster objects. If the extents, dimensions and resolutions match you can create a stack.

library(raster)
(L <- setNames(replicate(3, raster(matrix(runif(100), 10))), c('A', 'B', 'C')))
r <- stack(L[[1]])
  for(i in 2:length(L)) r <- addLayer(r, L[[i]])
class(r)
plot(r)

If you want separate raster (RasterLayer class) objects in the current R environment, you can use assign but, this is a somewhat risky function to work with.

library(raster)
(L <- setNames(replicate(3, raster(matrix(runif(100), 10))), c('A', 'B', 'C')))
  for(i in 1:length(L)) assign(names(L)[[i]], raster(L[[i]]) )
ls()
class(A)

Now you should have raster objects "A", "B" and "C" in your R environment. Although, keep in mind that for this to work names need to be assigned to the stack, which is not the case by default. You could replace names(L)[[i]] with code that generates a name based on i, something like paste0("r", i)

BTW, a better approach to your unlisting data.frame example would be to use do.call. ie., do.call("rbind", l)

1
  • I want them as individual raster objects, but the stack example is useful too.
    – derelict
    Sep 15, 2017 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.