How many non-NA values in each row for a matrix?

江枫思渺然 提交于 2019-12-02 17:52:55

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/29630036/how-many-non-na-values-in-each-row-for-a-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!