3

I would like to set the working directory of my scripts to the parent directory of the file.

My folder structure is projet/code/test.R

In the script 'test.R', I wrote:

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

However, the working directory will depend on where I source the script in the Terminal.

In the Terminal, I launched the script from the folders 'project' and 'project/code' and got the following results:

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

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

I would like a way of finding the directory in which the file is located.

My session info is here:

> 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

Thanks.

Best, C.

charlesdarwin
  • 717
  • 1
  • 9
  • 16

2 Answers2

2

This will change the directory to the source file location.

this.dir <- dirname(parent.frame(2)$ofile)
setwd(this.dir)
Kelli-Jean
  • 1,417
  • 11
  • 17
  • 1
    I used this code but got the following error: Error in dirname(parent.frame(2)$ofile) : a character vector argument expected Execution halted – charlesdarwin Sep 15 '17 at 12:48
  • And print(parent.frame(2)$ofile) gives NULL. – charlesdarwin Sep 15 '17 at 12:49
  • 1
    Ok, this would only work for you if you're sourcing this file from a file in 'project'. Do you have rstudio? If so, this should work: `setwd(dirname(rstudioapi::getActiveDocumentContext()$path))`. – Kelli-Jean Sep 15 '17 at 16:30
  • Unfortunately, it did not work. I got this error: Error: RStudio not running Execution halted even though I had RStudio running. Also, I want to run my files in a cluster, so this method would not be suitable. – charlesdarwin Sep 15 '17 at 18:58
  • 1
    I would put the output of `sessionInfo()` into your question. Maybe someone else will be able to help you out. – Kelli-Jean Sep 15 '17 at 19:20
1

I tried the dirname(parent.frame(2)$ofile) and dirname(sys.frame(2)$ofile) method but both do not work really well with me (I am on R 3.4.1, using RStudio, and Windows 10). I tried to source it in RStudio and R GUI. Also tried to ran it from command line.

This method below from user rakensi (https://stackoverflow.com/users/1021892/rakensi) works really well for me. Credits goes to him. Link to answer: Getting path of an R script.

Another method (test_v2.R) works for me using Rscript. Credit goes to user steamer25 (https://stackoverflow.com/users/93345/steamer25) and the link to the answer(Rscript: Determine path of the executing script).

test.R Run this using source(test.R) in Rstudio

## 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 Run this using 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())
addicted
  • 2,901
  • 3
  • 28
  • 49
  • Hi, unfortunately this did not work for me: ~/code: Rscript test.R character(0) Error in setwd(script.dir) : character argument expected Execution halted – charlesdarwin Sep 15 '17 at 12:37
  • 1
    @charlesdarwin how did you run the script? I would source this script in RStudio to get the expected result. Are you running it from cmd prompt (or maybe Terminal in your case)? – addicted Sep 18 '17 at 03:57
  • 1
    If you are running it from command prompt (using Rscript.exe), probably I have alternative solution that works (please see my edit in my answer above). Credit to user steamer25 (https://stackoverflow.com/users/93345/steamer25). – addicted Sep 18 '17 at 04:09
  • Hi addicted, your two solutions are very good, thank you. One works with source in Rstudio and the other with Rscript in the terminal. They are great. I am still looking for a solution that works when I run the code line by line. – charlesdarwin Sep 18 '17 at 14:15
  • @charlesdarwin Are you doing it in Rstudio? It does not make sense to me running it line by line because you want to know where the script is since you are running the script itself as a whole. But correct me if I am wrong. – addicted Sep 19 '17 at 10:32
  • I am doing it in all possible ways I think. I code in Rstudio and there I often run the code line by line or chunk by chunk in R Markdown files. Then, when the code is more mature, I test it locally on my laptop using the command line programme Rscript. Then, I move the code to a server and I run it there also using Rscript. I do not understand why it does not make sense? Now, I am moving to using R projects, so I open all my scripts in my R project and the working directory for the project is where the .Rproj file is. But I cannot run a script within an R project on the command line? – charlesdarwin Sep 19 '17 at 11:59
  • 1
    For normal codes, it makes a lot of sense running it line by line (that's how I always do it too btw). But for this script to check where the script's directory is, it does not make sense. If you are running line by line and you want to know your working directory, use `getwd()`. If you want to know where a certain script directory is, use `dirname("test.R")`. But if you want to the script to know its folder when it is being ran, you would have to run the whole script itself. – addicted Sep 20 '17 at 03:46