[R] conditionally merging adjacent rows in a data frame

Titus von der Malsburg malsburg at gmail.com
Tue Dec 8 17:14:46 CET 2009


On Tue, Dec 8, 2009 at 4:50 PM, Gray Calhoun <gray.calhoun at gmail.com> wrote:
> I think there might be a problem with this approach if roi, tid, rt,
> and mood are the same for nonconsecutive rows.

True, but I can use the index of my reshape solution. Aggregate was
the crucial ingredient.  Thanks both!

For the record, this is the full solution:

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

index  <- c(TRUE,diff(d$roi)!=0)
d2     <- d[index,]

index  <- cumsum(index)
d2$dur <- aggregate(d$dur, list(index=index), sum)[2]
d2$x   <- aggregate(d$x, list(index=index), mean)[2]




More information about the R-help mailing list