Dear Miluji,

something like this could help:

sapply(tapply(x$Value, x$ID, cumsum),

    function(x) x[seq(4, length(x), by=4)] - c(0, x[head(seq(4, length(x), by=4), -1)]))

1.) Step 1:

Compute the cumsum for each ID:

tapply(x$Value, x$ID, cumsum)


2.) Step 2:

- iterate over the resulting list and select each 4th value;

- you can either run a diff on this or subtract directly the (n-4) sum;


Note:

- you may wish to check if the last value is a multiple of 4;

- alternative: you can do a LOCF (last observation carried forward);


Hope this code example helps.


Sincerely,


Leonard

______________________________________________
R-help@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.

Reply via email to