【发布时间】:2016-04-28 09:08:24
【问题描述】:
我无法弄清楚这种(显然)简单的操作:
鉴于这两个不同的数据帧 df(A) (nrow=10,ncol=3) 和 df(B) (nrow=3,ncol=3)
df(A) df(B)
col1 col2 col3 col1 col2 col3
1 2 4 1 4 5
3 5 7 2 7 7
5 7 6 3 9 8
6 9 5.9
9 11 8
4.5 5.5 7.9
21 6.7 13.6
3.5 5 6
6 7.9 1
67 4 2
我想:
- 将 df(A) 中各列的值与对应列的 df(B) 的值相乘
- 然后从每一行开始对三个连续的结果求和。
我举个例子:
A[1,1]*B[1,1] + A[2,1]*B[2,1] + A[3,1]*B[3,1]= 1*1+3*2+5*3= 22 # first expected result
A[2,1]*B[1,1] + A[3,1]*B[2,1] + A[4,1]*B[3,1]= 3*1+5*2+6*3 = 31 # second expected result
A[3,1]*B[1,1] + A[4,1]*B[2,1] + A[5,1]*B[3,1]= 5*1+6*2+9*3 = 44 # third expected result
...
A[8,1]*B[1,1] + A[9,1]*B[2,1] + A[10,1]*B[3,1]= 3.5*1+6*2+67*3 = 216.5 # last expected result
以此类推,从df(A) 的每一列的每个值开始,直到最后一个可能的三元组。
我尝试使用这个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 in sum(temp) : invalid 'type' (list) of argument
In addition: There were 3 warnings (use warnings() to see them)
> warnings()
1: In 1:dim(A) : numerical expression has 2 elements: only the first used
2: In temp[j] <- A[i + (j - 1), ] * B[i + (j - 1), ] :
number of items to replace is not a multiple of replacement length
提前谢谢你 最好的
安娜
【问题讨论】: