'How do I group a list of numbers based on fixed recurrance
I have a list:
x <- c("1", "2", "2", "3", "3", "3", "2", "2", "3", "3", "3","2", "2", "2", "2")
What I need to do is make them shortened like this.
1 2 3 2 3 2 2
This is done because after 1, 2 appears 2 times and then 3 appears 3 times and then 2 appears 2 times and so on. This is fixed and it will not change. I have done this in an if else condition but that seems a bit too much for this. I'm hoping for some guidance on achieving this in a quick way.
Notice the last two 2s at the end of expected output. Another example to illustrate the expected output:
input: 3,3,3,3,3,3,2,2,2,2,2,2
output: 3,3,2,2,2
Solution 1:[1]
You can use rle() and repeat each value according to the ratio of its length to value.
with(rle(x), rep(values, lengths / as.numeric(values)))
# [1] "1" "2" "3" "2" "3" "2" "2"
Solution 2:[2]
inverse.rle(modifyList(a<-rle(as.numeric(x)), list(lengths = do.call("/", a))))
[1] 1 2 3 2 3 2 2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
