I need to decompose a vector into a series of x and repeat, I am not really sure what the proper term for this is. It is the inverse of the rep function. So a vector
[1,2,2,2,2,1,1,1,1,1,2,2] -> [1x1, 4x2, 5x1, 2x2]
I wrote a little function to do this, but I am sure there must be a more native 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));
The
rlefunction should do the trick:UPDATE As @TylerRinker commented, use
as.characteron factors: