I have a data.frame as below and I want to add a variable describing the longest consecutive count of 1 in the VALUE
variable observed in the group (i.e. longest consecutive rows with 1 in VALUE
per group).
GROUP_ID VALUE
1 0
1 1
1 1
1 1
1 1
1 0
2 1
2 1
2 0
2 1
2 1
2 1
3 1
3 0
3 1
3 0
So the output would look like this:
GROUP_ID VALUE CONSECUTIVE
1 0 4
1 1 4
1 1 4
1 1 4
1 1 4
1 0 4
2 1 3
2 1 3
2 0 3
2 1 3
2 1 3
2 1 3
3 1 1
3 0 1
3 1 1
3 0 1
Any help would be greatly appreciated!
with
likeDT[, v := with(rle(VALUE), max(lengths[values == 1])), by=GROUP_ID]
. I guess this (and your way as well) will throw an error if there are no 1s for a group, sincemax(1L[FALSE])
is not an int, though arguably that's OP's problem. – Personification