R command for setting working directory to source file location in Rstudio

旧城冷巷雨未停 提交于 2019-11-26 07:56:56

问题


I am working out some tutorials in R. Each R code is contained in a specific folder. There are data files and other files in there. I want to open the .r file and source it such that I do not have to change the working directory in Rstudio as shown below:

\"enter

Is there a way to specify my working directory automatically in R.


回答1:


To get the location of a script being sourced, you can use utils::getSrcDirectory or utils::getSrcFilename. So changing the working directory to that of the current file can be done with:

setwd(getSrcDirectory()[1])

This does not work in RStudio if you Run the code rather than Sourceing it. For that, you need to use rstudioapi::getActiveDocumentContext.

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

This second solution requires that you are using RStudio as your IDE, of course.




回答2:


I know this question is outdated, but I was searching for a solution for that as well and Google lists this at the very top:

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

put that somewhere into the file (best would be the beginning, though), so that the wd is changed according to that file.

According to the comments, this might not necessarily work on every platform (Windows seems to work, Linux/Mac for some). Keep in mind that this solution is for 'sourcing' the files, not necessarily for running chunks in that file.

see also get filename and path of `source`d file




回答3:


This answer can help:

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

Note: script must be sourced in order to return correct path

I found it in: https://support.rstudio.com/hc/communities/public/questions/200895567-can-user-obtain-the-path-of-current-Project-s-directory-

The BumbleBee´s answer (with parent.frame instead sys.frame) didn´t work to me, I always get an error.




回答4:


dirname(rstudioapi::getActiveDocumentContext()$path)

works for me but if you don't want to use rstudioapi and you are not in a proyect, you can use the symbol ~ in your path. The symbol ~ refers to the default RStudio working directory (at least on Windows).

If your RStudio working directory is "D:/Documents", setwd("~/proyect1") is the same as setwd("D:/Documents/proyect1").

Once you set that, you can navigate to a subdirectory: read.csv("DATA/mydata.csv"). Is the same as read.csv("D:/Documents/proyect1/DATA/mydata.csv").

If you want to navigate to a parent folder, you can use "../". For example: read.csv("../olddata/DATA/mydata.csv") which is the same as read.csv("D:/Documents/oldata/DATA/mydata.csv")

This is the best way for me to code scripts, no matter what computer you are using.




回答5:


For rstudio, you can automatically set your working directory to the script directory using rstudioapi like that:

library(rstudioapi)

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

This works when Running or Sourceing your file.

You need to install the package rstudioapi first. Notice I print the path to be 100% sure I'm at the right place, but this is optional.




回答6:


The solution

dirname(parent.frame(2)$ofile)

not working for me.

I'm using a brute force algorithm, but works:

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)

More easy when searching a directory:

Dirname <- "subdir_name"
Dirs <- list.dirs(path=file.path("~"),recursive=T)
dir_wd <- names(unlist(sapply(Dirs,grep,pattern=Dirname))[1])



回答7:


I was just looking for a solution to this problem, came to this page. I know its dated but the previous solutions where unsatisfying or didn't work for me. Here is my work around if interested.

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)



回答8:


I realize that this is an old thread, but I had a similar problem with needing to set the working directory and couldn't get any of the solutions to work for me. Here's what did work, in case anyone else stumbles across this later on:

# 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)

It's a bit convoluted, but basically this uses system commands to get the working directory and save it to dummyfile.txt, then R reads that file using data.table::fread. The rest is just cleaning up what got printed to the file so that I'm left with just the directory path.

I needed to run R on a cluster, so there was no way to know what directory I'd end up in (jobs get assigned a number and a compute node). This did the trick for me.




回答9:


I understand this is outdated, but I couldn't get the former answers to work very satisfactorily, so I wanted to contribute my method in case any one else encounters the same error mentioned in the comments to BumbleBee's answer.

Mine is based on a simple system command. All you feed the function is the name of your script:

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"));

The output from the function would look like "/Users/you/Path/To/Script". Hope this helps anyone else who may have gotten stuck.




回答10:


If you work on Linux you can try this:

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

It works for me.




回答11:


Most GUIs assume that if you are in a directory and "open", double-click, or otherwise attempt to execute an .R file, that the directory in which it resides will be the working directory unless otherwise specified. The Mac GUI provides a method to change that default behavior which is changeable in the Startup panel of Preferences that you set in a running session and become effective at the next "startup". You should be also looking at:

?Startup

The RStudio documentation says:

"When launched through a file association, RStudio automatically sets the working directory to the directory of the opened file." The default setup is for RStudio to be register as a handler for .R files, although there is also mention of ability to set a default "association" with RStudio for .Rdata and .R extensions. Whether having 'handler' status and 'association' status are the same on Linux, I cannot tell.

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




回答12:


dirname(parent.frame(2)$ofile)  

doesn't work for me either, but the following (as suggested in https://stackoverflow.com/a/35842176/992088) works for me in ubuntu 14.04

dirname(rstudioapi::getActiveDocumentContext()$path)



回答13:


In case you use UTF-8 encoding:

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

You need to install the package rstudioapi if you haven't done it yet.




回答14:


The here package provides the here() function, which returns your project root directory based on some heuristics.

Not the perfect solution, since it doesn't find the location of the script, but it suffices for some purposes so I thought I'd put it here.



来源:https://stackoverflow.com/questions/13672720/r-command-for-setting-working-directory-to-source-file-location-in-rstudio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!