我有两个数据帧:
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))
我想将test
中的每一列与test2
中的每个值相乘。输出看起来类似于:
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)
我通过调整this answer来管理解决方案,但可能会有一个更简单的解决方案。
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))]
答案 0 :(得分:2)
您需要根据自己的喜好调整列名称,但这应该有效:
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