Home > Mobile >  Change the sequence of adjacent pairs in a vector
Change the sequence of adjacent pairs in a vector

Time:12-01

I have a vector 'a'

a <- c(2, 1.2, 1.2, 2, 2, 2, 1.2, 1.2, 1.2, 2, 1.2, 2, 1.2, 1.2, 1.2, 1.2)

I need to create a new vector 'b' in which, wherever the number 1.2 is repeated as adjacent pairs should be present only once. The new vector 'b' should be

b <- c(2, 1.2, 2, 2, 2, 1.2, 1.2, 2, 1.2, 2, 1.2, 1.2)

Any suggestions using ifelse() or while().

CodePudding user response:

Using rle in combination with ifelse and ceiling :

a <- c(2, 1.2, 1.2, 2, 2, 2, 1.2, 1.2, 1.2, 2, 1.2, 2, 1.2, 1.2, 1.2, 1.2)

b <- with(rle(a), 
          rep(values, ifelse(values == 1.2, ceiling(lengths / 2), lengths)))

b
#>  [1] 2.0 1.2 2.0 2.0 2.0 1.2 1.2 2.0 1.2 2.0 1.2 1.2
  •  Tags:  
  • r
  • Related