Count number of rows until a value is reached

喜夏-厌秋 提交于 2019-12-12 06:26:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!