首页 文章

R命令用于在Rstudio中将工作目录设置为源文件位置

提问于
浏览
95

我正在研究R中的一些教程 . 每个R代码都包含在一个特定的文件夹中 . 那里有数据文件和其他文件 . 我想打开 .r 文件并获取它,这样我就不必更改Rstudio中的工作目录,如下所示:

enter image description here

有没有办法在R中自动指定我的工作目录

13 回答

  • 0

    我知道这个问题已经过时,但我也在寻找解决方案,谷歌在最上面列出了这个问题:

    this.dir <- dirname(parent.frame(2)$ofile)
    setwd(this.dir)
    

    把它放在文件的某个地方(尽管最好是开头),以便根据该文件更改wd .

    根据评论,这可能不一定适用于每个平台(Windows似乎可行,Linux / Mac适用于某些平台) . 请记住,此解决方案用于“获取”文件,而不一定用于在该文件中运行块 .

    另见get filename and path of sourced file

  • 37

    要获取源脚本的位置,可以使用 utils::getSrcDirectoryutils::getSrcFilename . 因此,可以使用以下命令将工作目录更改为当前文件的目录:

    setwd(getSrcDirectory()[1])
    

    如果您运行代码而不是源代码,这在RStudio中不起作用 . 为此,您需要使用 rstudioapi::getActiveDocumentContext .

    setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
    

    当然,第二种解决方案要求您使用RStudio作为IDE .

  • 0

    这个答案可以帮助:

    script.dir <- dirname(sys.frame(1)$ofile)
    

    注意:必须获取脚本才能返回正确的路径

    我找到了:https://support.rstudio.com/hc/communities/public/questions/200895567-can-user-obtain-the-path-of-current-Project-s-directory-

    BumbleBee的答案(使用parent.frame而不是sys.frame)对我不起作用,我总是收到错误 .

  • 3

    解决方案

    dirname(parent.frame(2)$ofile)
    

    不适合我 .

    我正在使用强力算法,但有效:

    File <- "filename"
    Files <- list.files(path=file.path("~"),recursive=T,include.dirs=T)
    Path.file <- names(unlist(sapply(Files,grep,pattern=File))[1])
    Dir.wd <- dirname(Path.file)
    

    搜索目录时更简单:

    Dirname <- "subdir_name"
    Dirs <- list.dirs(path=file.path("~"),recursive=T)
    dir_wd <- names(unlist(sapply(Dirs,grep,pattern=Dirname))[1])
    
  • 2
    dirname(rstudioapi::getActiveDocumentContext()$path)
    

    适合我,但如果你不想使用rstudioapi并且你不在proyect中,你可以在你的路径中使用符号〜 . 符号〜指的是默认的RStudio工作目录(至少在Windows上) .

    RStudio options

    如果您的RStudio工作目录是"D:/Documents",则 setwd("~/proyect1") 与setwd("D:/Documents/proyect1")相同 .

    设置完成后,可以导航到子目录: read.csv("DATA/mydata.csv") . 与 read.csv("D:/Documents/proyect1/DATA/mydata.csv") 相同 .

    如果要导航到父文件夹,可以使用 "../" . 例如: read.csv("../olddata/DATA/mydata.csv")read.csv("D:/Documents/oldata/DATA/mydata.csv") 相同

    这是我编写脚本的最佳方式,无论您使用的是什么计算机 .

  • 0

    我只是在寻找这个问题的解决方案,来到这个页面 . 我知道它已过时但以前的解决方案对我不满意或不起作用 . 如果有兴趣,这是我的工作 .

    filename = "your_file.R"
    filepath = file.choose()  # browse and select your_file.R in the window
    dir = substr(filepath, 1, nchar(filepath)-nchar(filename))
    setwd(dir)
    
  • 3

    对于rstudio,您可以使用rstudioapi自动将工作目录设置为脚本目录,如下所示:

    library(rstudioapi)
    
    # Getting the path of your current open file
    current_path = rstudioapi::getActiveDocumentContext()$path 
    setwd(dirname(current_path ))
    print( getwd() )
    

    这在运行或源文件时有效 .

    您需要先安装软件包rstudioapi . 请注意,我打印路径是100%确定我在正确的位置,但这是可选的 .

  • 5

    我知道这已经过时了,但我无法让前面的答案工作得非常令人满意,所以我想贡献我的方法,以防任何其他人遇到BumbleBee的答案中提到的相同错误 .

    我的基于一个简单的系统命令 . 您为该函数提供的所有内容都是脚本的名称:

    extractRootDir <- function(x) {
        abs <- suppressWarnings(system(paste("find ./ -name",x), wait=T, intern=T, ignore.stderr=T))[1];
        path <- paste("~",substr(abs, 3, length(strsplit(abs,"")[[1]])),sep="");
        ret <- gsub(x, "", path);
        return(ret);
    }
    
    setwd(extractRootDir("myScript.R"));
    

    函数的输出看起来像 "/Users/you/Path/To/Script" . 希望这有助于其他可能遇到困难的人 .

  • 5

    如果你在Linux上工作,你可以试试这个:

    setwd(system("pwd", intern = T) )

    这个对我有用 .

  • 6

    我意识到这是一个旧线程,但我遇到了类似的问题,需要设置工作目录,无法让任何解决方案适合我 . 这是什么工作,以防其他人在以后偶然发现:

    # SET WORKING DIRECTORY TO CURRENT DIRECTORY:
    system("pwd=`pwd`; $pwd 2> dummyfile.txt")
    dir <- fread("dummyfile.txt")
    n<- colnames(dir)[2]
    n2 <- substr(n, 1, nchar(n)-1)
    setwd(n2)
    

    这有点令人费解,但基本上这使用系统命令来获取工作目录并将其保存到dummyfile.txt,然后R使用data.table :: fread读取该文件 . 其余的只是清理打印到文件的内容,这样我只剩下目录路径 .

    我需要在集群上运行R,因此无法知道我最终会在哪个目录中(作业被分配了一个数字和一个计算节点) . 这对我有用 .

  • 2

    大多数GUI假设如果您在目录中并且“打开”,双击或以其他方式尝试执行.R文件,则它所在的目录将是工作目录,除非另有说明 . Mac GUI提供了一种更改默认行为的方法您可以在正在运行的会话中设置的“首选项”的“启动”面板中更改,并在下一次“启动”时生效 . 你也应该看看:

    ?Startup
    

    RStudio文档说:

    “当通过文件关联启动时,RStudio会自动将工作目录设置为打开文件的目录 . ”默认设置是将RStudio注册为.R文件的处理程序,尽管还提到了为RStudio设置与.Rdata和.R扩展名的默认“关联”的能力 . 在Linux上是否具有“处理程序”状态和“关联”状态是相同的,我无法分辨 .

    http://www.rstudio.com/ide/docs/using/workspaces

  • 2
    dirname(parent.frame(2)$ofile)
    

    对我来说也不起作用,但是以下(如https://stackoverflow.com/a/35842176/992088中所示)在ubuntu 14.04中对我有用

    dirname(rstudioapi::getActiveDocumentContext()$path)
    
  • 51

    如果您使用UTF-8编码:

    path <- rstudioapi::getActiveDocumentContext()$path
    Encoding(path) <- "UTF-8"
    setwd(dirname(path))
    

    如果尚未安装软件包rstudioapi,则需要安装软件包 .

相关问题