Decrease in sequence in R

Suppose you have a vector like this:

v <- c(1,1,1,2,2,2,2,1,1,3,3,3,3)

What is the best way to tear it down to a data.frame?

v.df <- data.frame(value=c(1,2,1,3),repetitions=c(3,4,2,4))

In a procedural language, I can just iterate over the loop and build data.frame as I go, but with a large dataset in R, this approach is inefficient. Any tips?

+3
source share
2 answers

or more simply

data.frame(rle(v)[])
+11
source
with(rle(v), data.frame(values, lengths))

should provide you with what you need.

values lengths
     1       3
     2       4
     1       2
     3       4
+8
source

Source: https://habr.com/ru/post/1749309/


All Articles