4

I have a matrix(raster) that I am computing the the mean of each row in this raster as:

  library (raster)
  r <- raster(nrows=10, ncols=10);r <- setValues(r, 1:ncell(r))

  # The x-values will be the mean of each row in the raster:
  xvals = rowMeans(as.matrix(r))

What I need is to know how many values were considered when computing the mean for each row (N)? Some pixels may have NA so the number of values will not be the same in each row.

6

You can use apply, which is actually the basis of the rowMeans function. If you are concerned that your row means are not correct because of NA's, just use the na.rm = TRUE argument in rowMeans.

library (raster)
  r <- raster(nrows=20, ncols=10)
  r[] <- runif(ncell(r))
  r[sample(1:ncell(r),10)] <- NA 

( r <- as.matrix(r) )

# Count number of NA values
apply(r, MARGIN = 1, FUN = function(x) length(x[is.na(x)]) )

# Calculate "true" n, accounting for NA's
apply(r, MARGIN = 1, FUN = function(x) length(x[!is.na(x)]) )
  • 4
    It's much faster (and even a little simpler) to use something like rowSums(!is.na(r)). – whuber Apr 14 '15 at 16:13
  • 1
    Yes, rowSums is faster (1.06s) than apply (8.49s) on a 10,000 x 10,000 matrix. But I would say that on a matrix that large, 9 seconds is not bad. I mostly like showing the guts of things for teaching purposes and think that optimization comes later. I think that to is good to know how to apply custom functions to the a matrix but, using rowSums is more straight forward and to the point of the OP's question. – Jeffrey Evans Apr 14 '15 at 18:00
  • 1
    Good points. There is both a pedagogical and a conceptual point to the rowSums solution in this case, though: the opportunities to capitalize on the type-punning that equates TRUE with 1 and FALSE with 0 are numerous and frequently overlooked. Here it amounts to the difference between counting objects (length(x[is.na(x)]))) and summing indicator functions (rowSums(!is.na(r)))). – whuber Apr 14 '15 at 21:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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