Rstudio에서 작업 디렉토리를 소스 파일 위치로 설정하기위한 R 명령
R에서 자습서를 만들고 있습니다. 각 R 코드는 특정 폴더에 포함되어 있습니다. 거기에 데이터 파일과 다른 파일이 있습니다. .r파일 을 열고 소스를 지정하여 아래와 같이 Rstudio에서 작업 디렉토리를 변경할 필요가 없습니다.

R에서 작업 디렉토리를 자동으로 지정하는 방법이 있습니까?
소스 스크립트의 위치를 확인하려면 utils::getSrcDirectory또는 을 사용할 수 있습니다 utils::getSrcFilename. 따라서 작업 디렉토리를 현재 파일의 디렉토리로 변경하려면 다음을 수행하십시오.
setwd(getSrcDirectory()[1])
소스 코드가 아닌 코드 를 실행 하면 RStudio에서 작동하지 않습니다 . 이를 위해서는을 사용해야 합니다.rstudioapi::getActiveDocumentContext
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
이 두 번째 솔루션은 물론 RStudio를 IDE로 사용해야합니다.
나는이 질문이 오래되었다는 것을 알고 있지만 그에 대한 해결책을 찾고 있었고 Google은 이것을 맨 위에 나열합니다.
this.dir <- dirname(parent.frame(2)$ofile)
setwd(this.dir)
파일의 어딘가에 넣으십시오 (그러나 가장 좋은 것은 시작일 것입니다) .wd는 해당 파일에 따라 변경됩니다.
의견에 따르면, 이것은 모든 플랫폼에서 작동하지 않을 수도 있습니다 (Windows는 Linux / Mac에서 작동하는 것으로 보입니다). 이 솔루션은 파일을 '소싱'하기위한 것이며 반드시 해당 파일에서 청크를 실행하기위한 것은 아닙니다.
`source`d 파일의 파일 이름과 경로를 참조하십시오.
이 답변이 도움이 될 수 있습니다.
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 사용)이 작동하지 않아 항상 오류가 발생합니다.
dirname(rstudioapi::getActiveDocumentContext()$path)
나를 위해 작동하지만 rstudioapi 를 사용하고 싶지 않고 proyect가 아닌 경우 경로에 ~ 기호를 사용할 수 있습니다. ~ 기호는 기본 RStudio 작업 디렉토리를 나타냅니다 (적어도 Windows에서는).
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")
이것은 어떤 컴퓨터를 사용하든 스크립트를 코딩하는 가장 좋은 방법입니다.
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.
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])
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)
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.
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.
If you work on Linux you can try this:
setwd(system("pwd", intern = T) )
It works for me.
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
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)
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.
here패키지는 제공하는 here()몇 가지 추론을 기반으로 프로젝트 루트 디렉토리를 반환하는 기능을.
스크립트의 위치를 찾지 못하기 때문에 완벽한 해결책은 아니지만 일부 목적으로는 충분하므로 여기에 넣을 것이라고 생각했습니다.
'Programing' 카테고리의 다른 글
| WebRequest의 본문 데이터 설정 (0) | 2020.07.24 |
|---|---|
| 장고. (0) | 2020.07.24 |
| console.writeline 및 System.out.println (0) | 2020.07.24 |
| JS에서 isNaN (null) == false 인 이유는 무엇입니까? (0) | 2020.07.24 |
| 플라스크 앱을 여러 개의 py 파일로 나누는 방법은 무엇입니까? (0) | 2020.07.24 |
