Adding a value after every nth element of a vector in R

There are many questions about how to extract every nth element of a vector, but I could not find one of how easy it is to add a value after every nth element of a vector. Is there an easy way to add a specific value after every nth element in a vector?

For example, suppose 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 v2 elements after every third v1 element, starting from 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" 
+7
vector r
source share
2 answers

You can make a long vector into a matrix with appropriate sizes; insert the top of the header; and then use c() to fold the matrix back into a vector.

Construction example:

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

Make a matrix and attach the title:

 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 smooth out:

 c(r) 
+7
source share

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

 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', transfer the output and convert matrix to vector with c .

 c(t(cbind(v2,matrix(v1, ncol=3, byrow=TRUE)))) 
+6
source share

All Articles