[R] Collapsing a vector/data-frame based on the previous values

jim holtman jholtman at gmail.com
Tue Jul 24 15:25:41 CEST 2012


Here is another way of doing it:

> states <- structure(list(Date = c("24/07/2012", "25/07/2012", "26/07/2012",
+ "27/07/2012", "28/07/2012", "24/07/2012", "25/07/2012", "26/07/2012",
+ "27/07/2012", "28/07/2012"), State = c(1L, 1L, 1L, 1L, 1L, -1L,
+ -1L, -1L, 1L, -1L)), .Names = c("Date", "State"), class = "data.frame",
+ row.names = c(NA,
+ -10L))
> # mark the state changes
> states$diff <- c(TRUE, diff(states$State) != 0)
> states[states$diff,]
         Date State diff
1  24/07/2012     1 TRUE
6  24/07/2012    -1 TRUE
9  27/07/2012     1 TRUE
10 28/07/2012    -1 TRUE


On Tue, Jul 24, 2012 at 2:40 AM, Raghuraman Ramachandran
<optionsraghu at gmail.com> wrote:
> Hello
>
> I have a data frame like this:
> dput(states)
> structure(list(Date = c("24/07/2012", "25/07/2012", "26/07/2012",
> "27/07/2012", "28/07/2012", "24/07/2012", "25/07/2012", "26/07/2012",
> "27/07/2012", "28/07/2012"), State = c(1L, 1L, 1L, 1L, 1L, -1L,
> -1L, -1L, 1L, -1L)), .Names = c("Date", "State"), class = "data.frame",
> row.names = c(NA,
> -10L))
>
>> State
>
>       Date State
> 1  24/07/2012     1
> 2  25/07/2012     1
> 3  26/07/2012     1
> 4  27/07/2012     1
> 5  28/07/2012     1
> 6  24/07/2012    -1
> 7  25/07/2012    -1
> 8  26/07/2012    -1
> 9  27/07/2012     1
> 10 28/07/2012    -1
>
> I wish to collapse it into a smaller one based on the state value. If state
> is 1 already then the second state (and the row) is to be removed till a
> new state is found and so on.. States can be 1 or -1 only. So in the
> previous example the new data frame should be:
>
>   Date State  24/07/2012 1  24/07/2012 -1  27/07/2012 1  28/07/2012 -1  Can
> someone help?
>
> Thx
> Raghu
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> 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
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.



More information about the R-help mailing list