I wish to count consecutive occurrence of any value and assign that count to that value in next column. Below is the example of input and desired output:
dataset <- data.frame(input = c("a","b","b","a","a","c","a","a","a","a","b","c"))
dataset$count <- c(1,2,2,2,2,1,4,4,4,4,1,1)
dataset
input count
a 1
b 2
b 2
a 2
a 2
c 1
a 4
a 4
a 4
a 4
b 1
c 1
With rle(dataset$input) I can just get number of occurrences of each value. But I want resulting output in above format.
My question is similar to: R: count consecutive occurrences of values in a single column But here output is in sequence and I want to assign the count itself to that value.
You can repeat the
lengthsargumentlengthstime inrleUsing
dplyr, we can uselagto create groups and then count the number of rows in each group.and with
data.tabledata
Make sure the
inputcolumn is character and notfactor.