Assuming that each day does start with 0, this should do it:
> t <- c(0,1,2,5,0,5,0,2,5)
> cumsum(t==0)
[1] 1 1 1 1 2 2 3 3 3>
On Sat, May 29, 2010 at 8:33 PM, Phyllis Hui-Min Chan
<h-mchan at hotmail.com> wrote:>
> 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.
>
> Thanks in advance for your yelp.
>
> Phyllis Chan.
>
> _________________________________________________________________
> Hotmail has tools for the New Busy. Search, chat and e-mail from your
inbox.
>
> N:WL:en-US:WM_HMP:042010_1
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem that you are trying to solve?