Jose Victor Zambrana
Jose Victor Zambrana

Reputation: 519

Insert elements into a vector at a given position, a given number of times

I have vector x <- c(1:50), and I want to insert y <- c(1,2) every 10nth position 5 times.

x <- c(1:50)
y <- c(1,2)
z <- c(seq(10,50,10))

The product has to be like this:

 1  2  3  4  5  6  7  8  9 10 1 2 11 12 13 14 15 16 17 18 19 20 1 2 21 22 23 24 25 26 27 28 29 30 1 2 31 32 33 34 35 36 37 38 39 40 1 2 41 42 43 44 45 46 47 48 49 50 1 2

I have tried with append, but it doesn't use "times"...

Upvotes: 2

Views: 4482

Answers (3)

lmo
lmo

Reputation: 38500

A simple solution is obtained by transforming x into a 10X5 matrix and then incrementally rbinding 1 and 2. c is used to return a vector.

c(rbind(rbind(matrix(x, 10), 1), 2))
 [1]  1  2  3  4  5  6  7  8  9 10  1  2 11 12 13 14 15 16 17 18 19 20  1  2 21 22 23 24
[29] 25 26 27 28 29 30  1  2 31 32 33 34 35 36 37 38 39 40  1  2 41 42 43 44 45 46 47 48
[57] 49 50  1  2

This can be generalize to more than 2 values by putting them in a list and using Reduce:

c(Reduce(rbind, list(matrix(x, 10), 1, 2)))

Following @akrun's comment, you can use y in place a 1,2 in the line above with

c(Reduce(rbind, append(list(matrix(x, 10)), y)))

or

c(Reduce(rbind, c(list(matrix(x, 10)), as.list(y))))

Upvotes: 2

B Williams
B Williams

Reputation: 2050

You can use append if you use a loop ala How to insert elements into a vector?

x <- 1:50
y <- c(1,2)
z <- c(seq(10,50,10))

 for(i in 0:(length(z)-1)) {
   out <- append(x, y, after=(z[i+1]+i))
 }

 out

But I like akrun's suggestion

Upvotes: 4

akrun
akrun

Reputation: 886938

We can split the 'x' into a list of vector based on a grouping index created with %/%``, concatenate (c) with the 'y' using 'Map and unlist the list to get the vector

unlist(Map(c, split(x, (x-1)%/%10), list(y)), use.names = FALSE)
#[1]  1  2  3  4  5  6  7  8  9 10  1  2 11 12 13 14 15 16 17 18 19 20  1  2 21
#[26] 22 23 24 25 26 27 28 29 30  1  2 31 32 33 34 35 36 37 38 39 40  1  2 41 42
#[51] 43 44 45 46 47 48 49 50  1  2

Upvotes: 6

Related Questions