2

I have a list of raster stacks that each raster stack contains unequal number of rasters. How can I sum up number of rasters in my list? I have tried length() but this only returns number of stacks in my list! example data:

library(raster)

#reproducible example
set.seed(987)

#our list of rasters
r.lst <- as.list(1:3)

# setting up list pf raster stacks
r1 <- raster(nrows = 1, ncols = 1, res = 0.5, xmn = -1.5, xmx = 1.5, ymn = -1.5, ymx = 1.5, vals = runif(36, 1, 5))
r.lst[[1]] <- stack(lapply(1:7, function(i) setValues(r1,runif(ncell(r1)))))
r.lst[[2]] <- stack(lapply(1:3, function(i) setValues(r1,runif(ncell(r1)))))
r.lst[[3]] <- stack(lapply(1:2, function(i) setValues(r1,runif(ncell(r1)))))
Armenia22
  • 145
  • 5

4 Answers4

2

One way to do this is as below:

# count sum rasters
n <- Reduce(`+`, lapply(r.lst, nlayers))
n
#[1] 12
Majid
  • 1,836
  • 9
  • 19
1

You can use nlayers to get the number of layers (rasters) in a stack and lapply to apply that function on every element of your list:

lapply(my.list.of.rasterstacks, nlayers)

To sum them all up:

sum(unlist(lapply(my.list.of.rasterstacks, nlayers)))
Where's my towel
  • 561
  • 2
  • 12
1

How about:

sum(sapply(r.lst, nlayers))
# [1] 12

or

sum(sapply(r.lst, dim)[3, ])
# [1] 12
zx8754
  • 52,746
  • 12
  • 114
  • 209
0

Without minimal data it's hard to answer

EDIT

With the example data, @Where's my towel has the correct answer

sum(unlist(lapply(r.lst, nlayers)))

Consider taking a look at this post on how to make a good reproducible example for future questions.

RoB
  • 1,833
  • 11
  • 23