'Adding value after every nth element of vector

There are many questions out there on how to extract every nth element of a vector, but I couldn't find one of how to easily add a value after every nth element of a vector. Is there an easy way to add a certain value after every nth element in a vector?

For example, lets say we have two vectors:

v1 <- paste0(letters[1:3], rep(1:5, each = 3))
> v1
[1] "a1" "b1" "c1" "a2" "b2" "c2" "a3" "b3" "c3" "a4" "b4" "c4" "a5" "b5" "c5"

v2 <- paste0("header", seq(1:5))
> v2
[1] "header1" "header2" "header3" "header4" "header5"

Now I want to add the elements of v2 after every third element of v1 beginning with the first. The result should look like this:

 [1] "header1" "a1" "b1" "c1" "header2" "a2" "b2" "c2" "header3" "a3" "b3" "c3" "header4" "a4" "b4" "c4" "header5" "a5" "b5" "c5"


Solution 1:[1]

You can make the long vector into a matrix with the appropriate dimensions; stick the header on top; and then use c() to flatten the matrix back into a vector.

Construct example:

v1 <- paste0(letters[1:3], rep(1:5, each = 3))
v2 <- paste0("header", seq(1:5))

Make the matrix and attach the header:

r <- rbind(v2,matrix(v1,ncol=length(v2)))
## "header1" "header2" "header3" "header4" "header5"
##    "a1"      "a2"      "a3"      "a4"      "a5"     
##    "b1"      "b2"      "b3"      "b4"      "b5"     
##    "c1"      "c2"      "c3"      "c4"      "c5"     

Now flatten it:

c(r)

Solution 2:[2]

We can split the 'v1' using a grouping variable (created with %/%) to form a list , then concatenate (c) the corresponding elements of 'v2' with the list using Map and unlist it.

unlist(Map(`c`, v2, split(v1, (seq_along(v1)-1)%/%3+1)), use.names=FALSE)
#[1] "header1" "a1"      "b1"      "c1"      "header2" "a2"      "b2"     
#[8] "c2"      "header3" "a3"      "b3"      "c3"      "header4" "a4"     
#[15] "b4"      "c4"      "header5" "a5"      "b5"      "c5"  

Or if the length of 'v1' is a multiple of '3', we can create a matrix with 'v1', cbind 'v2', transpose the output and convert the matrix to vector with c.

c(t(cbind(v2,matrix(v1, ncol=3, byrow=TRUE))))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ben Bolker
Solution 2 akrun