jeudi 20 septembre 2018

cumsum with reset at flagged column in r?

This is my first time asking a question so bear with me.

My dataset (df) is like so:

animal   azimuth   south   distance
 pb1      187.561   1       1.992 
 pb1      147.219   1       8.567
 pb1      71.032    0       5.754
 pb1      119.502   1       10.451
 pb2      101.702   1       9.227
 pb2      85.715    0       8.821

I want to create an additional column (df$cumdist) that adds cumulative distance, but within each individual animal and only if df$south==1. I want the cumulative sum to reset with df$south==0.

This is what I would like the result to be (done manually):

animal   azimuth   south   distance  cumdist
 pb1      187.561   1       1.992     1.992
 pb1      147.219   1       8.567     10.559 
 pb1      71.032    0       5.754     0 
 pb1      119.502   1       10.451    10.451
 pb2      101.702   1       9.227     9.227 
 pb2      85.715    0       8.821     0

This is code I tried to implement the cumsum:

swim.az$cumdist <- cumsum(ifelse(swim.az$south==1, swim.az$distance, 0))

While it successfully stops adding when df$south==0, it does not reset. Additionally, I know I will need to embed this in a for loop to subset by animal.

Thanks so much!

Aucun commentaire:

Enregistrer un commentaire