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"
The seq() method in R, is used to generate sequences, out of the objects they refer to. The seq() method, extracts a subset of the original vector, based on the constraints, that is the start and end index, as well as the number of steps to increment during each iteration.
Use stripe(n, from = m) to get every nth row/column starting at row/column m. Use dplyr functions like starts_with , contains and matches to specify columns (but not rows).
To append multiple elements to a Vector in R, use the append() method and pass the vector to the existing vector. It will spread out in the existing vector and add multiple elements to that vector.
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)
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))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With