[R] Find each time a value changes
Tim Clark
mudiver1200 at yahoo.com
Thu Feb 11 19:52:39 CET 2010
It was brought to my attention that the rle() answer to this question was not posted. The following gives the correct answer once the last value is deleted.
x<-seq(1:100)
y1<-rep(1,10)
y2<-rep(2,10)
y<-c(y1,y2,y1,y1,y1,y2,y1,y2,y1,y2)
xy<-cbind(x,y)
print(xy)
print(str(xy))
# SEE WHAT RLE GIVES
test <- rle(xy[,2])
print(str(test)
# USE JIM"S TRICK OF CUMULATIVE SUMMING
# TO GET THE LOCATIONS
result <- cumsum(c(1,rle(xy[,2])$lengths))
Tim Clark
Department of Zoology
University of Hawaii
--- On Wed, 2/10/10, Ben Tupper <ben.bighair at gmail.com> wrote:
> From: Ben Tupper <ben.bighair at gmail.com>
> Subject: Re: [R] Find each time a value changes
> To: r-help at r-project.org
> Cc: "Tim Clark" <mudiver1200 at yahoo.com>
> Date: Wednesday, February 10, 2010, 4:16 PM
> Hi,
>
> On Feb 10, 2010, at 8:58 PM, Tim Clark wrote:
>
> > Dear List,
> >
> > I am trying to find each time a value changes in a
> dataset. The
> > numbers are variables for day vs. night values, so
> what I am really
> > getting is the daily sunrise and sunset.
> >
> > A simplified example is the following:
> >
> > x<-seq(1:100)
> > y1<-rep(1,10)
> > y2<-rep(2,10)
> > y<-c(y1,y2,y1,y1,y1,y2,y1,y2,y1,y2)
> > xy<-cbind(x,y)
> >
> >
> > I would like to know each time the numbers change.
> > Correct answer should be:
> > x=1,11,21,51,61,71,81,91
> >
>
> I think this gets close...
>
> which(diff(y) != 0)
> [1] 10 20 50 60 70 80 90
>
> You'll need to fiddle to get exactly what you want.
>
> Cheers,
> Ben
>
>
>
> > I would appreciate any help or suggestions. It
> seems like it should
> > be simple but I’m stuck!
> >
> > Thanks,
> >
> > Tim
> >
> >
> > Tim Clark
> > Department of Zoology
> > University of Hawaii
> >
> >
> >
> >
> > ______________________________________________
> > 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.
>
>
More information about the R-help
mailing list