2
我有兩個p-times-n數組x
和missx
,其中x
包含任意數字,missx
是一個包含零和1的數組。我需要對missx
爲零的那些點執行遞歸計算。明顯的解決辦法是這樣的:Fortran的do循環在R中的任意循環如for循環?
do i = 1, n
do j = 1, p
if(missx(j,i)==0) then
z(j,i) = ... something depending on the previous computations and x(j,i)
end if
end do
end do
問題這種方法是大部分的時間missx
始終爲0,所以有相當多if
報表時總是爲真。
在R,我會做這樣的:
for(i in 1:n)
for(j in which(xmiss[,i]==0))
z[j,i] <- ... something depending on the previous computations and x[j,i]
有沒有辦法做到內環像在Fortran語言?我也嘗試一個版本是這樣的:
do i = 1, n
do j = 1, xlength(i) !xlength(i) gives the number of zero-elements in x(,i)
j2=whichx(j,i) !whichx(1:xlength(i),i) contains the indices of zero-elements in x(,i)
z(j2,i) = ... something depending on the previous computations and x(j,i)
end do
end do
這略微似乎比第一個解決方案更快(如果不是數定義xlength
和whichx
量),但有一些更聰明的方式來這就像將R版本,所以我不需要存儲那些xlength
和whichx
數組?
謝謝,我會檢查在哪裏構造。 – 2012-03-20 05:17:35