views:

123

answers:

2

Assume you have a vector like so:

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

How can it be best reduced to a data.frame like this?

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

In a procedural language I might just iterate through a loop and build the data.frame as I go, but with a large dataset in R such an approach is inefficient. Any advice?

+8  A: 
with(rle(v), data.frame(values, lengths))

should get you what you need.

values lengths
     1       3
     2       4
     1       2
     3       4
Greg
That is exactly the function I was thinking of; I just couldn't remember the name for the life of me! Thank you so much.
drknexus
+8  A: 

or more simply

data.frame(rle(v)[])
kohske
That's nice, even more succinct.
Greg
Another ways `data.frame(unclass(rle(v)))` or `as.data.frame.list(rle(v))`
Marek