按条件 (>) 计算每行的列数 [英] Count number of columns by a condition (>) for each row
问题描述
我正在尝试为矩阵的每一行计算出有多少列的值大于指定值.很抱歉我问了这个简单的问题,但我无法弄清楚.
I am trying to work out for each row of a matrix how many columns have values greater than a specified value. I am sorry that I am asking this simple question but I wasn't able to figure it out.
我已经从多年栅格的栅格堆栈中提取了我感兴趣的一些空间点的最高温度值.数据看起来类似于:
I have extracted maximum temperature values from a raster stack, of multiple years of rasters, for some spatial points I am interested in. The data looks similar to:
data <- cbind('1990' = c(25, 22, 35, 42, 44), '1991' = c(23, 28, 33, 40, 45), '1992' = c(20, 20, 30, 41, 43))
1990 1991 1992
1 25 23 20
2 22 28 20
3 35 33 30
4 42 40 41
5 44 45 43
我想得到每个位置温度高于 30 的年数,例如:
I want to end up with the number of years that the temperature was above 30 for each location, eg.:
yr.above
1 0
2 0
3 2
4 3
5 3
我尝试了一些东西,但它们没有用,而且非常不合逻辑(例如尝试 length(data[1:length(data), which(blah blah don't sense)),或 apply(data,1,length(data) > 30),我知道这些没有意义,但我有点卡住了.
I have tried a few things but they didn't work and were pretty illogical (e.g. trying length(data[1:length(data), which(blah blah doesn't make sense)), or apply(data, 1, length(data) > 30), I know these don't make sense but I am a bit stuck.
推荐答案
这将为您提供您正在寻找的向量:
This will give you the vector you are looking for:
rowSums(data > 30)
无论data
是矩阵还是data.frame,它都可以工作.此外,它使用矢量化函数,因此是一种优于使用 apply
的首选方法,后者只不过是一个(慢)for 循环.
It will work whether data
is a matrix or a data.frame. Also, it uses vectorized functions, hence is a preferred approach over using apply
which is little more than a (slow) for loop.
如果data
是一个data.frame,你可以将结果添加为一列:
If data
is a data.frame, you can add the result as a column by doing:
data$yr.above <- rowSums(data > 30)
或者如果 data
是一个矩阵:
or if data
is a matrix:
data <- cbind(data, yr.above = rowSums(data > 30))
您还可以创建一个全新的 data.frame:
You can also create a whole new data.frame:
data.frame(yr.above = rowSums(data > 30))
或者一个全新的矩阵:
cbind(yr.above = rowSums(data > 30))
这篇关于按条件 (>) 计算每行的列数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!