(rle)
x = c("a", "a", "1", "0", "b", "b", "b", "c", "1", "1")
r = rle(x)
> rle(x)
Run Length Encoding
lengths: int [1:6] 2 1 1 3 1 2
values : chr [1:6] "a" "1" "0" "b" "c" "1"
, ( "a" ) 2 , "1" .. , , "" , ,
> rep(seq_along(r$lengths), r$lengths)
[1] 1 1 2 3 4 4 4 5 6 6
Other answers are semi-mandatory as they rely on a column being a factor (); they fail when the column is actually a symbol ().
> diff(x)
Error in r[i1] - r[-length(r):-(length(r) - lag + 1L)] :
non-numeric argument to binary operator
The bypass was to map characters to integers along lines
> diff(match(x, x))
[1] 0 2 1 1 0 0 3 -5 0
Hmm, but by saying that I find that rle doesn't work on factors!
> f = factor(x)
> rle(f)
Error in rle(factor(x)) : 'x' must be a vector of an atomic type
> rle(as.vector(f))
Run Length Encoding
lengths: int [1:6] 2 1 1 3 1 2
values : chr [1:6] "a" "1" "0" "b" "c" "1"
source
share