Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...