A.Birdman A.Birdman - 9 months ago 70
R Question

Elementwise vector multiplication between all rows of two data frames / matrices

I have a set of models and need to generate estimates of survival for each model at different estimator levels. I first want to create the models I will be averaging across.

Here, the model set is represented by a matrix where columns are effects that may or may not be found in particular model,
rows are individual models, and cell values (1/0) turn the value on or off.

modset <- structure(list(A = c(1, 1), B = c(1, 1), C = c(1, 1), D = c(1,
1), E = c(0, 1), F = c(1, 0)), .Names = c("A", "B", "C", "D",
"E", "F"), row.names = c(2L, 4L), class = "data.frame")

I've also created a matrix which provides the desired values at which I need to run each model.

estvals <- structure(list(int = c(1L, 1L, 1L, 1L), age = c(6L, 18L, 6L,
18L), species = c(1L, 1L, 0L, 0L), Time = c(12L, 50L, 27L, 12L
), height = c(90L, 90L, 90L, 90L), LastNew = c(7L, 7L, 21L, 21L
)), .Names = c("int", "age", "species", "Time", "height", "LastNew"
), row.names = c(1L, 11L, 16L, 20L), class = "data.frame")

What I need to do now is create an output that is the result of essentially multiplying each row of estvals by each row of modset.
In my sample above, I would get 8 rows out (2 records for each estval record):

outs <- structure(list(int = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), age = c(6L,
6L, 18L, 18L, 6L, 6L, 18L, 18L), species = c(1L, 1L, 1L, 1L,
0L, 0L, 0L, 0L), Time = c(12L, 12L, 50L, 50L, 27L, 27L, 12L,
12L), height = c(0L, 90L, 0L, 90L, 0L, 90L, 0L, 90L), LastNew = c(7L,
0L, 7L, 0L, 21L, 0L, 21L, 0L)), .Names = c("int", "age", "species",
"Time", "height", "LastNew"), class = "data.frame", row.names = c(NA,

I haven't been able to come up with a solution. I've tried setting up something in apply() or sweep() but can't seem to get a function that will do what I'm asking.

Ultimately I am generating unconditional estimates for SE to build appropriate confidence intervals after model averaging. So each of the estvals above generates estimates of survival under various scenarios that will ultimately be shown graphically.

Answer Source

We can use

n1 <- nrow(modset)
n2 <- nrow(estvals)
outs <- modset[rep(1:n1, times = n2), ] * estvals[rep(1:n2, each = n1), ]

This will work whether you have matrices or data frames. The index I have generated using rep can also be obtained by expand.grid.