Reputation: 2533
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))
extent(r) = extent(c(xmn=-180,xmx=180,ymn=-90,ymx=90))
stepsize = (r@extent@ymax - r@extent@ymin) / r@nrows
yvals = seq(r@extent@ymax - stepsize / 2, r@extent@ymin, -stepsize)
The x-values will be the mean of each row in the raster:
xvals = rowMeans(as.matrix(r))
plot(xvals, yvals)
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.
Upvotes: 0
Views: 972
Reputation: 1678
Most Simply:
rowSums(!is.na(x))
(thanks to @Khashaa for this code).
Note the use of !
which equates to "not". This means that !is.na(x)
is evaluating the statement "values that are not equal to "NA".
Alternatively:
To return not NA you can change the code as follows:
sum(is.na(x)==FALSE)
You can modify the code using apply
to apply the code over the matrix as follows:
apply(d,2,function(x) sum(is.na(x))==TRUE))
where d
is a matrix such as:
d=matrix(c(1,NA,NA,NA),ncol=2,nrow=2)
Upvotes: 3