在我的for循环中,我需要删除RAM。所以我用rm()命令删除了一些对象。然后,我做,gc()但RAM仍然相同
因此,我使用.rs.restartR()代替gc()它,并且它起作用:重新启动R会话后,将删除我的RAM的足够部分。
我的问题是for循环,在R重新启动后会中断。您是否有想法在.rs.restartR()命令后自动进入for循环?
我偶然发现了这篇文章,因为rm()存在类似的问题,无法按预期清除内存。像您一样,如果我杀死了脚本,请使用rm(list = ls(all.names = TRUE))删除所有内容并重新启动,该脚本所花费的时间比最初要长。但是,使用.rs.restartR()重新启动会话,然后再次进行采购按预期工作。正如您所说,在循环内无法“刷新”会话。
我的解决方案是编写一个简单的bash脚本来调用.r文件。
假设您在R中有一个循环,循环从1到3,并且您希望在每次迭代后重新启动会话。我的bash脚本“ runR.sh”可能如下所示:
#!/bin/bash
for i in {1..3}
do
echo "Rscript myRcode.r $i" #check call to r script is as expected
Rscript myRcode.r $i
done
Run Code Online (Sandbox Code Playgroud)
然后在“ myRcode.r”的顶部:
args <- commandArgs()
print(args) #list the command line arguments.
myvar <- as.numeric(args[6])
Run Code Online (Sandbox Code Playgroud)
并删除您的for (myvar in...){},仅保留循环内容。
您将从中看到print(args),您的shell脚本输入是数组的第6个元素,因此args[6]在分配变量时在以下行中。如果要传递字符串,例如文件名,那么您当然不需要as.numeric。
./runR.sh然后运行将调用您的脚本并有望解决您的内存问题。唯一的小问题是,与使用.rs.restartR()时不同,您每次都必须重新加载软件包,并且可能不得不重复通常只运行一次的其他位。
在我的情况下它可以正常工作,我很想听听其他经验丰富的R / bash用户是否对此解决方案有任何疑问...
小智 6
通过将迭代保存为外部文件,并编写一个调用自身的 rscript,可以在 rstudio 内的 for 循环内重新启动会话。该示例需要执行以下步骤。
#Save an the iteration as a separate .RData file in the working directory.
iter <- 1
save(iter, file="iter.RData")
Run Code Online (Sandbox Code Playgroud)
创建一个脚本,该脚本调用自身进行一定次数的迭代。将以下脚本保存为“test_script.R”
###load iteration
library(rstudioapi)
load("iter.RData")
###insert function here.
time_now <- Sys.time()
###save output of function to a file.
save(time_now, file=paste0("time_", iter, ".Rdata"))
###update iteration
iter <- iter+1
save(iter, file="iter.RData")
###restart session calling the script again
if(iter < 5){
restartSession(command='source("test_script.R")')
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1313 次 |
| 最近记录: |