2016-06-09 30 views
1

我有兩個列表(A和B),長度3的每一個都包括5個矢量我也有一個3×3矩陣Z.使用mapply對矢量的列表執行操作:用索引規範麻煩

欲使用B和Z對A的元素執行操作,並將其輸出到3x5矩陣。我能爲循環成功地做到這使用如下

#Create two lists of vectors 
A = list(c(1,2,1), c(2,1,2), c(3,2,2),c(1,2,5),c(1,4,2)) 
B = list(c(2,3,1), c(1,3,4), c(2,5,2), c(2,4,1),c(1,4,1)) 
#Create 3x3 matrix 
Z = rbind(c(2,3,5),c(3,2,3), c(1,1,1)) 

#initialize empty 3x5 matrix 
Y = matrix(NA,3,5) 

for (i in 1:3) 
{ 
    for (j in 1:5) 
    { 
    #Take the ith element of the jth vector from A, and divide it by 
    #the dot product of the jth vector from B and the ith row of Z 
    Y[i,j] = A[[j]][i]/sum(B[[j]]*Z[i,]) 
    } 
} 

這回報(對Y)

  [,1]  [,2]  [,3]  [,4]  [,5] 
[1,] 0.05555556 0.06451613 0.10344828 0.04761905 0.05263158 
[2,] 0.13333333 0.04761905 0.09090909 0.11764706 0.28571429 
[3,] 0.16666667 0.25000000 0.22222222 0.71428571 0.33333333 

我試圖找出如何使用mapply,使這個更有效。

到目前爲止,我有這樣的:

mapply(function(x,y,z) x/sum(y*z), x=A,y=B,z = Z) 

但這不能正常工作。我認爲也許將任務分解成兩個單獨的mapply可能會有所訣竅,也許我需要重新組織矩陣和列表,以便索引匹配。我在應用系列功能方面取得了一些成功,但我還不夠流暢,無法找出如何最好地解決這個問題。我會很感激任何指導。

回答

1

我決定把它分成兩步,就像你想的那樣。這是一種方法:

BZ <- lapply(B, FUN = function(y) 
    apply(Z, 1, FUN = function(x) sum(y*x))) 

mapply(function(x,y) x/y, x = A, y = BZ) 

      [,1]  [,2]  [,3]  [,4]  [,5] 
[1,] 0.05555556 0.06451613 0.10344828 0.04761905 0.05263158 
[2,] 0.13333333 0.04761905 0.09090909 0.11764706 0.28571429 
[3,] 0.16666667 0.25000000 0.22222222 0.71428571 0.33333333 
+0

啊!非常感謝。你的回答不僅解決了我的問題,而且還將幫助我在申請家庭中變得更好。非常感激! – spacediver