How can a rowwise matrix operation avoid a loop ("purrr-ified")?

Viewed 45

Is it possible to avoid using a for-loop in the following example? I have attempted to use purrr::pmap at some point but it seemed more complicated than this solution. Similar questions exist but more concerning lists or dataframe columns.

The example comes from the context of methods of moment estimation (GMM), though it is highly stylized here.

# Data
Z <- matrix(c(1:15), nrow = 5, ncol = 3)
r <- rnorm(5)  
g_bar <- matrix(1:3, ncol = 1)

# First observation
g <-  (Z[1,] * r[1]) - g_bar

# All other observations
for (i in 2:nrow(Z)) {  
  g_i <- (Z[i,] * r[i]) - g_bar
  g <- cbind(g, g_i)
}

g # A 3x5 matrix 
2 Answers

Here is another solution:

g <- t(Z * r) - c(g_bar)

If the calculation is precisely that in the question then there is a better answer already but if the actual calculation is more complex then perhaps this generalizes to it:

mapply(function(z, r) z * r - g_bar, as.data.frame(t(Z)), r)

or

mapply(function(z, r, g) z * r - g, as.data.frame(t(Z)), r, 
  MoreArgs = list(g = g_bar))
Related