[R] Collapsing a vector/data-frame based on the previous values
arun
smartpink111 at yahoo.com
Wed Jul 25 04:14:16 CEST 2012
Hello,
Try this:
#dat1 - data
diff2<-c(TRUE,ifelse(diff(dat1$State)>0|diff(dat1$State)<0,TRUE,FALSE))
dat1[diff2,1:2]
# Date State
#1 24/07/2012 1
#6 24/07/2012 -1
#9 27/07/2012 1
#10 28/07/2012 -1
A.K.
----- Original Message -----
From: Raghuraman Ramachandran <optionsraghu at gmail.com>
To: R Project Help <r-help at r-project.org>
Cc:
Sent: Tuesday, July 24, 2012 2:40 AM
Subject: [R] Collapsing a vector/data-frame based on the previous values
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.
More information about the R-help
mailing list