【发布时间】:2016-01-14 10:31:50
【问题描述】:
我有这两个数据框:df(A) (nrow=10,ncol=2) 和 df(B) (nrow=3,ncol=2)。
df(A) df(B)
col1 col2 col1 col2
1 2 13 34
3 5 22 56
5 7 30 42
6 9
9 11
4.5 5.5
21 6.7
3.5 5
6 7.9
67 4
在这种模式下是否可以将 df(A) 中的每个值相乘和相加? :
示例:
A[1,1]*B[1,1] + A[1,1]*B[1,2] + A[1,1]*B[1,3]= 1*13+1*22+1*30= 65
A[2,1]*B[1,1] + A[2,1]*B[1,2] + A[2,1]*B[1,3]= 3*13+3*22+3*30 = 195
and so on for all row in A&col1 for B$col1
A$col2 和 B$col2 相同
A[1,2]*B[1,1] + A[1,2]*B[1,2] + A[1,2]*B[1,3]= 2*34+2*56+2*42= 264
A[2,2]*B[1,1] + A[2,2]*B[1,2] + A[2,2]*B[1,3]= 5*34+5*56+5*42=660
and so on for all row in A&col2 for B$col2
预期的结果是df(C),有 2 列和 10 行。
我对@987654327@ 很感兴趣,但它适用于整行或整列。这个例子是简化的,但我真正的df 是最大的,有10 列和1000 多行。
循环 for 有可能吗?
我以这种方式尝试循环for:
temp <- rep(NA,3)
my_matrix <- matrix(0,ncol=ncol(A),nrow=nrow(A))
for (i in 1:nrow(A)){
for (j in 1:3){
temp(j) <- A(i+j-1)*B(i+j-1)
}
my_matrix(i) <- sum(temp)
}
但是 R 回复 :Error: could not find function "A"or
attempt to apply non-function`
提前谢谢你。
【问题讨论】:
-
请显示预期输出
-
您能更好地解释一下您的意思吗?是否要根据 A$col3 和 B$col3 中的条件将 A$col1 * B$col1 相乘。
-
我编辑了我以前的帖子,现在我希望问题更好更清晰。如果你能帮助我提前谢谢你