【问题标题】:Set the working directory to the parent folder of the script file in R将工作目录设置为R中脚本文件的父文件夹
【发布时间】:2018-02-24 01:06:44
【问题描述】:

我想将脚本的工作目录设置为文件的父目录。

我的文件夹结构是 projet/code/test.R

在脚本'test.R'中,我写道:

getwd()
setwd(dirname(getwd()))
print(getwd())

但是,工作目录将取决于我在终端中获取脚本的位置。

在终端中,我从文件夹 'project' 和 'project/code' 启动脚本,得到以下结果:

~/Documents/project: Rscript code/test.R 
~/Documents/project
~/Documents

~/Documents/project/code: Rscript test.R
~/Documents/project/code
~/Documents/project

我想要一种查找文件所在目录的方法。

我的会话信息在这里:

> sessionInfo()
R version 3.4.0 (2017-04-21)
Platform: x86_64-apple-darwin16.5.0 (64-bit)
Running under: macOS Sierra 10.12.6

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libLAPACK.dylib

locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] bindrcpp_0.2 dplyr_0.7.2 

loaded via a namespace (and not attached):
 [1] Biobase_2.36.2             jsonlite_1.5              
 [3] bit64_0.9-7                splines_3.4.0             
 [5] Formula_1.2-2              assertthat_0.2.0          
 [7] stats4_3.4.0               latticeExtra_0.6-28       
 [9] blob_1.1.0                 GenomeInfoDbData_0.99.0   
[11] yaml_2.1.14                RSQLite_2.0               
[13] backports_1.1.0            lattice_0.20-35           
[15] glue_1.1.1                 digest_0.6.12             
[17] GenomicRanges_1.28.4       RColorBrewer_1.1-2        
[19] XVector_0.16.0             checkmate_1.8.3           
[21] colorspace_1.3-2           htmltools_0.3.6           
[23] Matrix_1.2-10              plyr_1.8.4                
[25] DESeq2_1.16.1              XML_3.98-1.9              
[27] pkgconfig_2.0.1            pheatmap_1.0.8            
[29] genefilter_1.58.1          zlibbioc_1.22.0           
[31] purrr_0.2.3                xtable_1.8-2              
[33] scales_0.4.1               BiocParallel_1.10.1       
[35] htmlTable_1.9              tibble_1.3.3              
[37] annotate_1.54.0            IRanges_2.10.2            
[39] ggplot2_2.2.1              SummarizedExperiment_1.6.3
[41] nnet_7.3-12                BiocGenerics_0.22.0       
[43] lazyeval_0.2.0             survival_2.41-3           
[45] magrittr_1.5               evaluate_0.10.1           
[47] memoise_1.1.0              foreign_0.8-69            
[49] tools_3.4.0                data.table_1.10.4         
[51] matrixStats_0.52.2         stringr_1.2.0             
[53] S4Vectors_0.14.3           munsell_0.4.3             
[55] locfit_1.5-9.1             cluster_2.0.6             
[57] DelayedArray_0.2.7         AnnotationDbi_1.38.2      
[59] compiler_3.4.0             GenomeInfoDb_1.12.2       
[61] rlang_0.1.2                grid_3.4.0                
[63] RCurl_1.95-4.8             rstudioapi_0.6            
[65] htmlwidgets_0.9            rmarkdown_1.6             
[67] bitops_1.0-6               base64enc_0.1-3           
[69] labeling_0.3               gtable_0.2.0              
[71] DBI_0.7                    R6_2.2.2                  
[73] gridExtra_2.2.1            knitr_1.17                
[75] bit_1.1-12                 rprojroot_1.2             
[77] bindr_0.1                  Hmisc_4.0-3               
[79] stringi_1.1.5              parallel_3.4.0            
[81] Rcpp_0.12.12               geneplotter_1.54.0        
[83] rpart_4.1-11               acepack_1.4.1

谢谢。

最好的,C.

【问题讨论】:

    标签: r directory


    【解决方案1】:

    这会将目录更改为源文件位置。

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

    【讨论】:

    • 我使用了这段代码,但得到以下错误: dirname(parent.frame(2)$ofile) 中的错误:预期的字符向量参数执行停止
    • 而 print(parent.frame(2)$ofile) 给出 NULL。
    • 好的,这仅适用于您从“项目”中的文件中获取此文件的情况。你有rstudio吗?如果是这样,这应该可以工作:setwd(dirname(rstudioapi::getActiveDocumentContext()$path)).
    • 不幸的是,它不起作用。我收到此错误:错误:RStudio 未运行 即使我运行了 RStudio,执行也已停止。另外,我想在集群中运行我的文件,所以这种方法不适合。
    • 我会将sessionInfo() 的输出放入您的问题中。也许其他人可以帮助你。
    【解决方案2】:

    我尝试了 dirname(parent.frame(2)$ofile)dirname(sys.frame(2)$ofile) 方法,但两者都不适用于我(我在 R 3.4.1 上,使用 RStudio 和 Windows 10)。我试图在 RStudio 和 R GUI 中获取它。还尝试从命令行运行它。

    以下来自用户 rakensi (https://stackoverflow.com/users/1021892/rakensi) 的方法对我来说非常有效。学分归他所有。 回答链接:Getting path of an R script

    另一种方法 (test_v2.R) 使用 Rscript 对我有用。归功于用户 steamer25 (https://stackoverflow.com/users/93345/steamer25) 和答案链接 (Rscript: Determine path of the executing script)。

    test.R 在 Rstudio 中使用 source(test.R) 运行它

    ## Run this from ~/Documents/project/code or directory of your choice
    script.dir <- getSrcDirectory(function(x) {x})
    print(script.dir)
    # gives you ~/Documents/project/code
    setwd(script.dir)
    

    test_v2.R 使用 Rscript.exe 运行它

    thisFile <- function() {
        cmdArgs <- commandArgs(trailingOnly = FALSE)
        needle <- "--file="
        match <- grep(needle, cmdArgs)
        if (length(match) > 0) {
            # Rscript
            return(normalizePath(sub(needle, "", cmdArgs[match])))
        } else {
            # 'source'd via R console
            return(normalizePath(sys.frames()[[1]]$ofile))
        }
    }
    script.dir <- dirname(thisFile())
    setwd(script.dir)
    print(getwd())
    

    【讨论】:

    • 嗨,不幸的是,这对我不起作用:~/code: Rscript test.R character(0) setwd(script.dir) 中的错误:预期字符参数执行停止
    • @charlesdarwin 你是如何运行脚本的?我会在 RStudio 中获取此脚本以获得预期的结果。您是从 cmd 提示符(或者在您的情况下可能是终端)运行它吗?
    • 如果您是从命令提示符运行它(使用 Rscript.exe),我可能有其他可行的解决方案(请在上面的答案中查看我的编辑)。感谢用户 steamer25 (stackoverflow.com/users/93345/steamer25)。
    • 嗨上瘾,你的两个解决方案都很好,谢谢。一个在 Rstudio 中使用源代码,另一个在终端中使用 Rscript。他们都是伟大的。当我逐行运行代码时,我仍在寻找一种可行的解决方案。
    • 对于普通代码,逐行运行它很有意义(顺便说一句,我总是这样做)。但是让这个脚本检查脚本的目录在哪里,这是没有意义的。如果您正在逐行运行并且想知道您的工作目录,请使用getwd()。如果您想知道某个脚本目录在哪里,请使用dirname("test.R")。但是如果你想让脚本在运行时知道它的文件夹,你就必须自己运行整个脚本。
    猜你喜欢
    • 2015-04-17
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    相关资源
    最近更新 更多