[R] keep only the first value of a numeric sequence
Richard M. Heiberger
rmh at temple.edu
Mon Dec 15 14:18:53 CET 2014
we can speed this up a lot
> system.time(for (i in 1:2000) ifelse(c(0, diff(data$mydata)) != 1, 0, 1))
user system elapsed
0.122 0.012 0.132
> system.time(for (i in 1:2000) as.numeric( c(0, diff(data$mydata))==1))
user system elapsed
0.073 0.007 0.078
> ifelse(c(0, diff(data$mydata)) != 1, 0, 1)
[1] 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0
> as.numeric( c(0, diff(data$mydata))==1)
[1] 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0
>
On Mon, Dec 15, 2014 at 7:18 AM, Jorge I Velez <jorgeivanvelez at gmail.com> wrote:
> Dear jeff6868,
>
> Here is one way:
>
> ifelse(with(data, c(0, diff(mydata))) != 1, 0, 1)
>
> You could also take a look at ?rle
>
> HTH,
> Jorge.-
>
>
>
> On Mon, Dec 15, 2014 at 9:33 PM, jeff6868 <geoffrey_klein at etu.u-bourgogne.fr
>> wrote:
>>
>> Hello dear R-helpers,
>>
>> I have a small problem in my algorithm. I have sequences of "0" and "1"
>> values in a column of a huge data frame, and I just would like to keep the
>> first value of each sequences of "1" values, such like in this example:
>>
>> data <-
>>
>> data.frame(mydata=c(0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,0,0,0,0,1,1,1,1,1,1,1),final_wished_data=c(0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0))
>>
>> Any easy way to do this?
>>
>> Thanks everybody!
>>
>>
>>
>>
>> --
>> View this message in context:
>> http://r.789695.n4.nabble.com/keep-only-the-first-value-of-a-numeric-sequence-tp4700774.html
>> Sent from the R help mailing list archive at Nabble.com.
>>
>> ______________________________________________
>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> 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.
>>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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