如何在R中的异步期货中更改工作目录 [英] How to change working directory in asynchronous futures in R

查看:100
本文介绍了如何在R中的异步期货中更改工作目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在将来的处理器中更改工作目录,执行一些操作,然后退出.问题是我无法设置工作目录.

I am trying to change working directory in a future processor, carry out some operations, and exit. The problem is I am not able to set a working directory.

以下玩具示例可以正常工作

The following toy example works fine

library(future)
dirNames <- as.character(c(1:4))
sapply(dirNames, function(x) if(!dir.exists(x)) dir.create(x))
plan(multiprocess, workers=2)
b <- list()

for(i in seq_along(dirNames)){
  sleeptime <- 10
  if(i > 3) sleeptime <- 50
  a <- future({
    # setwd(dirNames[i])
    Sys.sleep(sleeptime)
    return(2)
  })
  print(i)
  b[[dirNames[i]]] <- a
}
lapply(b, resolved)
lapply(b[1:2], value)
lapply(b, value)

但是如果我取消注释第11行,则在运行代码时出现以下错误

but if I uncomment line 11 then I get following error when running the code

setwd(dirNames [i])错误:无法更改工作目录

Error in setwd(dirNames[i]) : cannot change working directory

如何成功更改工作目录?

How can I change working directory successfully?

推荐答案

我在研究脚本时想出了一个解决方案.

I figured out a solution while playing around with the script.

library(future)
dirNames <- as.character(c(1:4))
sapply(dirNames, function(x) if(!dir.exists(x)) dir.create(x))
plan(multiprocess, workers=2)
b <- list()

for(i in seq_along(dirNames)){
  sleeptime <- 10
  if(i > 3) sleeptime <- 50
  a <- future({
    currDir <- getwd()
    on.exit(setwd(currDir))
    setwd(dirNames[i])
    Sys.sleep(sleeptime)
    return(2)
  })
  print(i)
  b[[dirNames[i]]] <- a
}
lapply(b, resolved)
lapply(b[1:2], value)
lapply(b, value)

我相信在前几次迭代中设置的worker工作目录将永久设置为新目录,以进行剩余的迭代,因此将来的路径(参考旧目录)将不起作用.

I believe that the workers working directory once set in the first few iterations remains permanently set to new directory for remaining iterations and hence future paths (with reference to old directory) do not work.

这篇关于如何在R中的异步期货中更改工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆