Sequence reduction in R

最后都变了- 提交于 2019-12-07 07:30:53

问题


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?


回答1:


or more simply

data.frame(rle(v)[])



回答2:


with(rle(v), data.frame(values, lengths))

should get you what you need.

values lengths
     1       3
     2       4
     1       2
     3       4


来源:https://stackoverflow.com/questions/3010790/sequence-reduction-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!