How to Merge 2 Vectors Alternating Indexes

How to merge 2 vectors alternating indexes?

This will work using rbind :

c(rbind(a, b))

For example:

a = c(1,2,3)
b = c(11,12,13)

c(rbind(a,b))

#[1] 1 11 2 12 3 13

Cross merge two vectors

a <- c(1, 2, 3, 4)
b <- c(5, 6, 7, 8)

ab <- as.vector(matrix(c(a, b), nrow = 2, byrow = TRUE))
ab
[1] 1 5 2 6 3 7 4 8

Combining 2 vectors in alternating way by step of 4 in R

We can do this by splitting. Create a function to create a grouping variable with gl that increments at blocks of 'n' (here n is 4), then split both the vectors into a list, use Map to concatenate the corresponding list elements and unlist the list to create a vector

f1 <- function(x, n) split(x, as.integer(gl(length(x), n, length(x))))
unlist( Map(c, f1(a, 4), f1(b, 4)), use.names = FALSE)
#[1] 723 680 2392 2063 1 2 3 4
#[9] 721 746 2053 2129 5 6 7 8

Or if the lengths are the same, then we can rbind and concatenate after creating a matrix

c(rbind(matrix(a, nrow =4), matrix(b, nrow = 4)))
#[1] 723 680 2392 2063 1 2 3 4 721 746 2053 2129 5 6 7 8

combine two vectors in correct order

v1 <- c("a","j","d")
v2 <- c("book","tree","river")
c(rbind(v1,v2))
# [1] "a" "book" "j" "tree" "d" "river"

Merge two arrays with alternating values

You could iterate the min length of both array and build alternate elements and at the end push the rest.

var array1 = ["a", "b", "c", "d"],    array2 = [1, 2],    result = [],    i, l = Math.min(array1.length, array2.length);    for (i = 0; i < l; i++) {    result.push(array1[i], array2[i]);}result.push(...array1.slice(l), ...array2.slice(l));
console.log(result);

Pythonic way to combine (interleave) two lists in an alternating fashion?

Here's one way to do it by slicing:

>>> list1 = ['f', 'o', 'o']
>>> list2 = ['hello', 'world']
>>> result = [None]*(len(list1)+len(list2))
>>> result[::2] = list1
>>> result[1::2] = list2
>>> result
['f', 'hello', 'o', 'world', 'o']

join two lists in R offset by a lag of 1

You can do :

as.list(c(rbind(l1, l2)))

#[[1]]
#[1] "a"

#[[2]]
#[1] "d"

#[[3]]
#[1] "b"

#[[4]]
#[1] "e"

#[[5]]
#[1] "c"

#[[6]]
#[1] "f"


Related Topics



Leave a reply



Submit