Home > Enterprise >  How do I group a list of numbers based on fixed recurrance
How do I group a list of numbers based on fixed recurrance

Time:04-30

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

CodePudding user response:

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"

CodePudding user response:

  inverse.rle(modifyList(a<-rle(as.numeric(x)), list(lengths = do.call("/", a))))
[1] 1 2 3 2 3 2 2
  •  Tags:  
  • r
  • Related