每次迭代后存储矩阵

Storing matrix after every iteration

我有以下代码。

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

gcm() 是一些函数,其中 returns 一个基于 ij 值的数字,因此 R 具有所有值。但是这个计算需要很多时间。我的机器电源中断了几次,因此我不得不重新开始。有人可以帮忙吗,我怎样才能在每次迭代后将 R 保存在某个地方,以确保安全?非常感谢任何帮助。

如果您想保存 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 函数,

Returns a vector or array or list of values obtained by applying a function to margins of an array or matrix

您希望每个单元格 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-方法再次变慢,请尝试考虑 snowfall 包,它允许您使用并行计算来遵循 apply-方法。可以找到 snowfall 用法的介绍 in this pdf,请查看页面 5,尤其是 6

您可以使用saveRDS()函数将每次计算的结果保存在一个文件中。

要了解 savesaveRDS 之间的区别,这里有一个 link 我觉得有用。 http://www.fromthebottomoftheheap.net/2012/04/01/saving-and-loading-r-objects/