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:
我想在test2中将每个列乘以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)
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))]
1 个解决方案
#1
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
#1
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