I am trying to count the number of times a value occurs consecutively for a given variable. I would like to store these values in another variable. It is similar to this question here but I would like to perform it for each factor--there are over 75,000 different factors.
Asked
Active
Viewed 88 times
1 Answers
1
Here is the answer I used: I wanted to count the number of strings of ones and zeros and used the following code.
out.full <- within(df, {
smaller <- unlist(lapply(split(var1, var2), function(x) sequence(rle(x)$lengths)))
cum.ones <- replace(smaller, var1 == 1,NA)
cum.zeroes <- replace(smaller, var1 == 0, NA)
rm(smaller)
})

jvalenti
- 604
- 1
- 9
- 31