Repeat pattern in R (integers down and up)

Viewed 67

I would like to create a repeat pattern from 5 to 0 then goes back to 5, 3 times, so I want 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, ..., 5 How can I do this is R??

I know rep

(seq(from=a, by=b, length=c),d)

function, but don't know how to use it with this pattern... Can anyone help , me, I would like to use

x <- 5
y <- 3
2 Answers

We can use seq with rev. As we don't want repetitions of 5 and 0 twice, I have not included them in the seq command. We repeat the seq(4, 1) and its reverse (rev) thrice.

a = seq(4, 1)
c(rep(c(5, a, 0, rev(a)), 3), 5)

#[1] 5 4 3 2 1 0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5

Here is another idea. We can create the vector with 5:0 and 0:5. We can then repeat the vector three times. Finally, we can use rle to create run-length encoding, modify the length larger than 1 to be 1, and use inverse.rle to create the final output.

x <- rep(c(5:0, 0:5), 3)
y <- rle(x)
y$lengths[y$lengths > 1] <- 1
z <- inverse.rle(y)
z
[1] 5 4 3 2 1 0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5
Related