问题
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)
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)
Thanks in advance!
回答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
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.
来源:https://stackoverflow.com/questions/38062796/count-number-of-rows-until-a-value-is-reached