Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

r - 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.

question from:https://stackoverflow.com/questions/66048893/group-the-near-same-numbers-of-a-vector

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...