Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

repeat sequences from vector

Tags:

indexing

r

Say I have a vector like so:

vector <- 1:9
#$ [1]  1  2  3  4  5  6  7  8  9

I now want to repeat every i to i+x sequence n times, like so for x=3, and n=2:

#$ [1] 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 7 8 9

I'm accomplishing this like so:

index <- NULL
x <- 3
n <- 2
for (i in 1:(length(vector)/3)) {
  index <- c(index, rep(c(1:x + (i-1)*x), n))
}
#$ [1] 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 7 8 9

This works just fine, but I have a hunch there's got to be a better way (especially since usually, a for loop is not the answer).

Ps.: the use case for this is actually repeating rows in a dataframe, but just getting the index vector would be fine.

like image 280
maxheld Avatar asked Mar 25 '26 09:03

maxheld


1 Answers

You can try to first split the vector, then use rep and unlist:

x <- 3  # this is the length of each subset sequence from i to i+x (see above)
n <- 2  # this is how many times you want to repeat each subset sequence
unlist(lapply(split(vector, rep(1:(length(vector)/x), each = x)), rep, n), use.names = FALSE)
#  [1] 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 7 8 9

Or, you can try creating a matrix and converting it to a vector:

c(do.call(rbind, replicate(n, matrix(vector, ncol = x), FALSE)))
#  [1] 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 7 8 9
like image 60
A5C1D2H2I1M1N2O1R2T1 Avatar answered Mar 27 '26 21:03

A5C1D2H2I1M1N2O1R2T1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!