I have a data frame on which I compute the length encoding for a specific column. The values ββof the dir column are either -1, 0, or 1.
dir.rle <- rle(df$dir)
Then I take the execution lengths and compute the segmented aggregate amounts from another column in the data frame. I am using a for loop, but I feel that there should be a way to do this more intelligently.
ndx <- 1 for(i in 1:length(dir.rle$lengths)) { l <- dir.rle$lengths[i] - 1 s <- ndx e <- ndx+l tmp[s:e,]$cumval <- cumsum(df[s:e,]$val) ndx <- e + 1 }
The length of the dir run determines the start, s and end, e for each run. The above code works, but it doesn't look like idiomatic R code. I feel that there must be another way to do this without a loop.
source share