我有寫過R函數ComplexResult
的情況,該函數計算計算結果較高的結果,其他兩個單獨的函數稍後將使用LaterFuncA
和LaterFuncB
。關於如何存儲函數的結果以便稍後在R中使用的良好做法
我想存儲的ComplexResult
結果的地方,這樣既LaterFuncA
和LaterFuncB
可以使用它,它並不需要重新計算。 ComplexResult
的結果是一個大矩陣,只需要計算一次,然後再重新使用。 R是我第一次進入函數式編程的世界,所以有興趣瞭解它被認爲是什麼好習慣。我的第一條思路如下:
# run ComplexResult and get the result
cmplx.res <- ComplexResult(arg1, arg2)
# store the result in the global environment.
# NB this would not be run from a function
assign("CachedComplexResult", cmplx.res, envir = .GlobalEnv)
這樣做是否正確?我能想到的唯一的另一種方法是具有大的「包裝」功能,例如:
MyWrapperFunction <- function(arg1, arg2) {
cmplx.res <- ComplexResult(arg1, arg2)
res.a <- LaterFuncA(cmplx.res)
res.b <- LaterFuncB(cmplx.res)
# do more stuff here ...
}
想法?我是否正在朝着正確的方向與上述任一方向走?還是有一個更狡猾的選項C? :)
'cmplx.res < - ComplexResult(arg1,arg2)'你正在做一個分配,所以你不需要做2次。在我的實踐中,存儲大型表格/矩陣的最佳方式是在「.txt」文件中。 'write.table'和'read.table'工作非常快 –
'save(object,file =「filename」)'如果你想再次使用這個對象'load(file =「filename」)' – The6thSense