2016-11-16 107 views
1

我試圖在代碼的末尾存儲來自forloop的n.I矩陣的輸出數據,但我確定輸出矩陣有問題。它給了我所有相同的值,無論是0還是1.我知道print(SS)正在輸出正確的值,並且可以看到forloop正常工作。用於輸出數據的循環存儲

有沒有人有任何建議如何解決矩陣,或任何我能夠存儲數據從forloop的方式?提前致謝!

c=0.2 
As=1  
d=1  
d0=0.5 
s=0.5 
e=0.1  
ERs=e/As  

C2 = c*As*exp(-d*s/d0)    

#Island States (Initial Probability)     
SS=0      


for(i in 1:5) { 
    if (SS > 0) { 
    if (runif(1, min = 0, max = 1) < ERs){ 
     SS = 0 
    } 
    } 
    else { 
    if (runif(1, min = 0, max = 1) < C2) { 
     SS = 1 
    } 
    } 
print(SS) 
} 
n.I=matrix(c(SS), nrow=i, ncol=1, byrow=TRUE) 

回答

4

這裏的高效解決方案不是使用循環。這是沒有必要的,因爲整個任務可以很容易地矢量化。

Z =runif(100,0,1) 
as.integer(x <= Z) 
#[1] 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 1 0 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 
#[70] 0 0 0 0 0 0 0 1 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 
+0

請問您是否可以詳細說明該功能究竟意味着什麼?它似乎給了我什麼for循環產生類似的價值(即這種方式)。我在學習R方面仍然很陌生,並且注意到人們似乎儘可能避免使用forloops。這是爲什麼?非常感謝羅蘭! –

+0

您應該閱讀「R介紹」。這會立即創建100個隨機值,並將您的x值與所有這些值同時進行比較。所得到的邏輯向量(TRUE/FALSE值)然後變成一個整數向量(1/0值)。向量化意味着循環發生在編譯後的代碼中,循環速度快很多個數量級。矢量化代碼通常也更易讀(如這個例子很好地演示)。 – Roland

0

您可以將它們保存在列表中。效率不高,但完成了工作。 list [[1]]表示如果要檢索它,則保存在列表中的第一個元素。

list_pos <- list() # create the list out of the for loop 
    for(i in 1:100) { 
    c=0.10 #colonization rate 
    A=10 #Area of all islands(km^2) 
    d=250 #Distance from host to target (A-T) 
    s=0.1 #magnitude of distance 
    d0=100 #Specific "half distance" for dispersal(km) 
    C1 = c*A*exp(-d/d0) #Mainland to Target colonization 
    Z =runif(1,0,1) 
    x <- C1*A 


    if(x <= Z) { 
      list_pos[[i]] <- print("1") # Here you can store the 1 results.print is actually not necessary. 
    } 
    if(x >= Z){ 
      list_pos[[i]] <- print("0") # Here you can store the 0 results.print is actually not necessary. 
    } 
}