Mark
Mark

Reputation: 1769

Merge two arrays in R alternating their elements

Suppose I have two arrays of the same length (e.g. 1000), array1 and array2, that look like

   array 1= 0.7828479 0.7782587 0.697296 0.7847533 0.7963145 0.7742886 0.6367928 ...
   array 2= 0.5324373 -0.5765472 -0.5020422 -0.3265736 -0.09438474 0.1368133 ...

and I want to merge them into a new array that looks like:

   first 20 elements of array 1 (i.e. array1[1], array1[2],...,array1[20])
   first 10 elements of array 2 (i.e. array2[1], array2[2],...,array2[10])
   second 20 elements of array 1 (i.e. array1[21], array1[2],...,array1[40])
   second 10 elements of array 2 (i.e. array2[11], array2[2],...,array2[20])

and so on, until all the elements of one of the arrays had been used up. Then array1 will always be used up first and the resulting vector will have 20 and 10 consecutive items from array 1 and 2 respectively each time.

Upvotes: 1

Views: 519

Answers (1)

MartijnVanAttekum
MartijnVanAttekum

Reputation: 1435

It seems that you use vectors then. Does this work? (I use some randomly initialized vectors). This assumes that the size of your vectors is a multiple of the number of elements you want to take each time.

vec1 <- rnorm(100)
vec2 <- rnorm(100)
step1 <- 20
step2 <- 10
as.vector(sapply(0 : (length(vec1) / step1 - 1), function(idx){
  c(vec1[1 : step1 + (idx * step1)], vec2[1 : step2 + (idx * step2)])}))

Upvotes: 1

Related Questions