From this post, Alternate, interweave or interlace two vectors, a convenient way to combine two vectors alternately was shown:
x <- 1:3 ; y <- 4:6
c(rbind(x, y)) # [1] 1 4 2 5 3 6
However, this method is only applicable to the condition that the two vectors have the same lengths. Now I want to find a general way to do that.
Here is my idea:
fun <- function(x, y, n) {...}
x
andy
are two vectors with the same type and their lengths can be different.n
means the interval of alternating, and.
The expected output:
x <- 1:5 ; y <- c(0, 0, 0)
fun(x, y, n = 1) # 1 0 2 0 3 0 4 5
fun(x, y, n = 2) # 1 2 0 3 4 0 5 0
fun(x, y, n = 5) # 1 2 3 4 5 0 0 0
Thanks for help.