首页 > 解决方案 > Group the near same numbers of a vector

问题描述

I have the following vector:

c("a", "a", "b", "a", "a", "c", "c", "c")

and I would like to split its elements into several groups according to the near same value. the result is like this:

[[1]] ("a", "a"), [[2]]("b"), [[3]]("a", "a"), [[4]]("c", "c", "c")

although the element of group 1 and group 3 is the same, they are not neighbor. so they belong to different group. I try to using for loop to do it, but it is not good enough.

标签: rrun-length-encoding

解决方案


Use this code

vec <- c("a", "a", "b", "a", "a", "c", "c", "c")

v2 <- rle(vec)

split(vec,rep(1:length(v2$lengths), v2$lengths)) 

$`1`
[1] "a" "a"

$`2`
[1] "b"

$`3`
[1] "a" "a"

$`4`
[1] "c" "c" "c"


推荐阅读