# [R] Count the number of consecutive 1's

Phyllis Hui-Min Chan h-mchan at hotmail.com
Sun May 30 02:33:41 CEST 2010

```Hi All,
We have a raw dataset that, on the sampling time column, for example:
t <- c(0,1,2,5,0,5,0,2,5)
And we need to create a second column that indicates the day of the sampling, so the end result of what we want is a vector:
1,1,1,1,2,2,3,3,3
Additional information that might simplify the matter is that, for each day, the time starts with zero and ends with 5.

I am a beginner with R.   So far I have:

t <- c(0,1,2,5,0,5,0,2,5)
rownum = length(t)
y <- NULL
y0 <- NULL
y1 <- NULL
x <- ifelse (t!=5,x<-1,x<-0)
for (i in 1:rownum){
if (x==1)  {
y <- y+x
} else {y+1 then
y0<-sum(y) then
y=0
}
y1 <- c(y1,y0)
}
y2 <- y1
y2 <- y2[y2!=0]
y2
Day <- NULL
for (i in 1:length(y2)){
z <- rep(i,y2[i])
Day <- c(Day,z)}
Day # want 1,1,1,1,2,2,3,3,3 here

I think my if else statement has syntax error and that's what is causing the problem.  What I am trying to do with the loop is, to start counting the number in x, and whenever it reaches a x=zero (same as t=5), then sum up how many 1's it has so far and store it into new variable y0 and then reset y to zero to start counting again.

Suggestions about alternative ways to do this is also welcome.