mikefc

I’m looking for a better, neater, more R-like solution to this - please hit me up on twitter.

At the moment, I can’t even include a benchmark screenshot as I only have just the one idea on how to do this!

Interleaving a vector with a matrix of the same width

I have a vector a row-vector and matrix of equal width

vec <- c(101, 102, 103)
mat <- matrix(c(1, 2, 3,
                4, 5, 6,
                7, 8, 9), nrow = 3, byrow = TRUE)

Expected output after interleaving by column

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1  101    2  102    3  103
[2,]    4  101    5  102    6  103
[3,]    7  101    8  102    9  103

My solution

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#' Interleave a matrix and a row-vector of the same width
#'
#'  * Create an empty matrix of double the width
#'  * Copy over the given matrix
#'  * Copy over the vector (using a for loop. quelle horreur!)
#'
#' @param m NxM matrix
#' @param v vector of length M
#'
#' @return N x M*2 matrix
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
interleave <- function(m, v) {
  res <- matrix(0, ncol = 2L * ncol(m), nrow = nrow(m))
  res[,c(T, F)] <- m
  for (i in seq_along(v)) {
    res[,2L * i] <- v[i]
  }
  
  res
}
interleave(mat, vec)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1  101    2  102    3  103
[2,]    4  101    5  102    6  103
[3,]    7  101    8  102    9  103

Summary

Anyone have any better ideas?