Search code examples
rrep

Get (1, 2, 3, 4, 2, 3, 4, 3, 4, 4) from (1, 2, 3, 4) in R


I have vector

z1 <- c(1, 2, 3, 4) 

and want to get from it another vector

z2 <- c(1, 2, 3, 4,
           2, 3, 4,
              3, 4,
                 4)

I've tried different variants of rep() function, but get only this

z3 <- rep(z1, times=seq(length(z1), 1))

z3 <- c(1, 1, 1, 1,
           2, 2, 2, 
              3, 3,
                 4)

Also z2 get be done with for() loops

temp <- z1
res <- c()

for (i in 1:length(z1)){
    
    res <- c(res, temp)
    temp <- temp[-1]
    
}

res <- c(1, 2, 3, 4,
            2, 3, 4,
               3, 4,
                  4)

But is there any ways to transform z1 to z2 with one string built-in functions like rep()?


Solution

  • You can try sapply + unlist + tail like below

    > unlist(sapply(-seq_along(z1), tail, x = c(NA, z1)))
     [1] 1 2 3 4 2 3 4 3 4 4