我不能與此(顯然)找出簡單地種操作:如何R中創建一個for循環這一特殊計算
給定這兩個diferent dataframes df(A)
(nrow = 10,NcoI位= 3)和df(B)
(nrow = 3,NcoI位= 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
預先感謝您 最佳
安娜