矩阵的每一行中有多少个非 NA 值? [英] How many non-NA values in each row for a matrix?

查看:29
本文介绍了矩阵的每一行中有多少个非 NA 值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵(栅格),我正在计算这个栅格中每一行的平均值:

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)

我需要知道在计算每行 (N) 的平均值时考虑了多少个值?某些像素可能具有 NA,因此每行中的值数量不会相同.

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.

推荐答案

最简单的:

rowSums(!is.na(x))(感谢@Khashaa 提供此代码).

rowSums(!is.na(x)) (thanks to @Khashaa for this code).

注意 ! 的用法等同于not".这意味着 !is.na(x) 正在评估语句等于NA"的值.

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".

或者:

要返回非 NA,您可以按如下方式更改代码:

To return not NA you can change the code as follows:

sum(is.na(x)==FALSE)

您可以使用 apply 修改代码以将代码应用于矩阵,如下所示:

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))

其中 d 是一个矩阵,例如:

where d is a matrix such as:

d=matrix(c(1,NA,NA,NA),ncol=2,nrow=2)

这篇关于矩阵的每一行中有多少个非 NA 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆