问题描述
我正在尝试计算行数,直到达到一个值为止。
这是一个示例数据集:
I am trying to count the number of rows until a value is reached.Here's an example dataset:
trialtype <- c(1,1,0,1,1,0,0,1,0,1)
RT <- c(100,200,300,400,500,600,700,800,900,950)
fakedata <- cbind(trialtype,RT)
我想做的是对于每个trialtype = 0,计算在它上面的行数,其中trialtype = 1直到到达列的开头(对于第一个0)或直到它命中另一个0(其余0),然后创建一个包含行数的新向量。
因此,对于该数据集,我的虚假结果看起来像是
What I would like to do is for every trialtype = 0, count the number of rows above it where trialtype = 1 until it hits the beginning of the column (for the first 0) or until it hits another 0 (for the rest of the 0s), and create a new vector that contains the number of rows.So my fake result for this data set would be something that looks like
x <- c(1,2,3,4)
numones <- c(2,2,0,1)
fakeresults <- cbind(x,numones)
谢谢!
推荐答案
首先,使用相等性比较和。然后,计算在索引向量上减去1,并加上零以在第一个索引之前提供正确的距离。
First, get the indexes of the zeroes using an equality comparison and which()
. Then, compute diff()
minus one on the index vector, with a prepended zero to provide the correct distance prior to the first index.
zis <- which(fakedata[,'trialtype']==0);
data.frame(x=seq_along(zis),numones=diff(c(0L,zis))-1L);
## x numones
## 1 1 2
## 2 2 2
## 3 3 0
## 4 4 1
这仅在输入列中只有零和一的情况下有效。如果还有其他值,而您只想对零之前的 1 进行计数,则需要一个更复杂的解决方案。
This will only work if there are only zeroes and ones in the input column. If there are other values, and you're interested only in counting ones prior to zeroes, then a more complex solution will be needed.
这篇关于计算行数,直到达到一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!