2017-08-06 104 views
0

我有以下代碼。每次迭代後存儲矩陣

for(i in 1:100) 
{ 
    for(j in 1:100) 
    R[i,j]=gcm(i,j) 
} 

gcm()是一些函數,它返回一個基於的ij等的值的數目,R具有所有值。但是這個計算需要很長時間。我的機器電源中斷了好幾次,因此我不得不重新開始。有人可以請幫忙,我怎樣才能在每次迭代後將R保存在某個地方,以保證安全?任何幫助,高度讚賞。

回答

0

如果你想保存R-工作區看看?save?save.image(使用第一個保存對象的子集,第二個保存您的全盤工作區)。

你編輯的代碼看起來應該像

for(i in 1:100) 
{ 
    for(j in 1:100) 
    R[i,j]=gcm(i,j) 
    save.image(file="path/to/your/file.RData") 
} 

關於你的代碼服用大量的時間,我會建議嘗試?apply功能,

返回向量或數組或列表通過將函數應用於陣列或矩陣的邊界而獲得的值

你想gmc爲,每個單元,這意味着你要應用它的行和列的每個組合運行協調

R = 100; # number of rows 
C = 100; # number of columns 
M = expand.grid(1:R, 1:C); # Cartesian product of the coordinates 
# each row of M contains the indexes of one of R's cells 
# head(M); # just to see it 

# To use apply we need gmc to take into account one variable only (that' not entirely true, if you want to know how it really works have a look how at ?apply) 
# thus I create a function which takes into account one row of M and tells gmc the first cell is the row index, the second cell is the column index 
gmcWrapper = function(x) { return(gmc(x[1], x[2])); } 

# run apply which will return a vector containing *all* the evaluated expressions 
R = apply(M, 1, gmcWrapper); 

# re-shape R into a matrix 
R = matrix(R, nrow=R, ncol=C); 

如果apply -approach再次緩慢嘗試考慮snowfall包,這將允許您遵循apply -approach使用並行計算。到snowfall用法的介紹可以發現in this pdf,看5頁面和6特別