I have two dataframes:
output1 <- data.frame('x_10' = c(1,2,4,7,9),
'x_20' = c(3,6,2,8,11))
output2 <- data.frame('z_10' = c(2),
'z_20' = c(3))
I would like to multiply each column in test
with each value in test2
. The output would look similar to this:
finaloutput <- data.frame('x_10_z_10' = output1$x_10*output2$z_10,
'x_10_z_20' = output1$x_10*output2$z_20,
'x_20_z_10' = output1$x_20*output2$z_10,
'x_20_z_20' = output1$x_20*output2$z_20)
I have managed a solution by tweaking this answer, but likely there is a simpler solution out there.
output3 <- data.frame(output1, output2)
finaloutput <- cbind(output3^2, do.call(cbind,combn(colnames(output3), 2,
FUN= function(x) list(output3[x[1]]*output3[x[2]]))))
colnames(finaloutput)[-(seq_len(ncol(output3)))] <- combn(colnames(output3), 2,
FUN = paste, collapse=":")
finaloutput <- finaloutput[,c(grepl("(?=.*x)(?=.*z)", names(finaloutput), perl = TRUE))]