Compress vector in (reverse rep)

I need to decompose the vector into a series of x and repeat, I'm not quite sure what the correct term is for this. This is the inverse of the rep function. So the vector

 [1,2,2,2,2,1,1,1,1,1,2,2] -> [1x1, 4x2, 5x1, 2x2] 

I wrote a small function for this, but I'm sure there should be a more proprietary way:

 invrep <- function(y){ numy <- as.numeric(y); newpoints <- which(c(T,diff(numy) != 0)); x <- y[newpoints]; times <- diff(c(newpoints, length(numy)+1)); return(list(x=x, times=times)); } myvec <- factor(floor(runif(50,0,3)), levels=0:2, labels=c("blue", "yellow", "red")); myrep <- invrep(myvec); identical(myvec, rep(myrep$x, myrep$times)); 
+6
source share
1 answer

The rle function should do the trick:

 > x <- c(1,2,2,2,2,1,1,1,1,1,2,2) > y <- rle(x) > y Run Length Encoding lengths: int [1:4] 1 4 5 2 values : num [1:4] 1 2 1 2 > inverse.rle(y) [1] 1 2 2 2 2 1 1 1 1 1 2 2 > rep(y$values, y$lengths) [1] 1 2 2 2 2 1 1 1 1 1 2 2 

UPDATE . Commenting on @TylerRinker, use as.character for factors:

 myvec <- factor(sample.int(3,50,TRUE), levels=1:3, labels=c("blue", "yellow", "red")) x <- rle(as.character(myvec)) y <- inverse.rle(x) 
+10
source

Source: https://habr.com/ru/post/915722/


All Articles