0

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 testwith 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))]
SlyGrogger
  • 317
  • 5
  • 16

1 Answers1

2

You'll need to tweak the column names to your liking, but this should work:

do.call(cbind, lapply(output2, function(x) output1 * x))
#   z_10.x_10 z_10.x_20 z_20.x_10 z_20.x_20
# 1         2         6         3         9
# 2         4        12         6        18
# 3         8         4        12         6
# 4        14        16        21        24
# 5        18        22        27        33
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485