[R] conditionally merging adjacent rows in a data frame
Titus von der Malsburg
malsburg at gmail.com
Tue Dec 8 13:50:30 CET 2009
Hi, I have a data frame and want to merge adjacent rows if some condition is
met. There's an obvious solution using a loop but it is prohibitively slow
because my data frame is large. Is there an efficient canonical solution for
that?
> head(d)
rt dur tid mood roi x
55 5523 200 4 subj 9 5
56 5523 52 4 subj 7 31
57 5523 209 4 subj 4 9
58 5523 188 4 subj 4 7
70 4016 264 5 indic 9 51
71 4016 195 5 indic 4 14
The desired result would have consecutive rows with the same roi value merged.
dur values should be added and x values averaged, other values don't differ in
these rows and should stay the same.
> head(result)
rt dur tid mood roi x
55 5523 200 4 subj 9 5
56 5523 52 4 subj 7 31
57 5523 397 4 subj 4 8
70 4016 264 5 indic 9 51
71 4016 195 5 indic 4 14
There's also a solution using reshape. It uses an index for blocks
d$index <- cumsum(c(TRUE,diff(d$roi)!=0))
melts and then casts for every column using an appropriate fun.aggregate.
However, this is a bit cumbersome and also I'm not sure how to make sure that
I get the original order of rows.
Thanks for any suggestion.
Titus
More information about the R-help
mailing list