現在のスクリプトのパスに作業ディレクトリをプログラムで設定したいのですが、まず現在のスクリプトのパスを取得する必要があります。 RStudioメニューはありません
現在のスクリプトのパスを取得
current_path = ...retrieve the path of current script ...
setwd(current_path)
は、これまでのところ、私が試した:
は、だから私は行うことができるようにしたいと思い
initial.options <- commandArgs(trailingOnly = FALSE)
file.arg.name <- "--file="
script.name <- sub(file.arg.name, "", initial.options[grep(file.arg.name, initial.options)])
script.basename <- dirname(script.name)
script.name returns NULL
source("script.R", chdir = TRUE)
Returns: Error in file(filename, "r", encoding = encoding) : cannot open the connection In addition: Warning message: In file(filename, "r", encoding = encoding) : cannot open file '/script.R': No such file or directory
dirname(parent.frame(2)$ofile)
Returns: Error in dirname(parent.frame(2)$ofile) : a character vector argument expected ...because parent.frame is null
frame_files <- lapply(sys.frames(), function(x) x$ofile)
frame_files <- Filter(Negate(is.null), frame_files)
PATH <- dirname(frame_files[[length(frame_files)]])
Returns: Null because frame_files is a list of 0
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))
}
}
Returns: Error in path.expand(path) : invalid 'path' argument
また、私はhere、here、hereとhereからすべての答えを見ました。 喜びはありません。あなただけのディレクトリをしたい場合はRStudioでRStudio 1.1.383
EDIT: It would be great if there was no need for an external library to achieve this.
おそらく 'source(" /script.R "、chdir = TRUE)'は、ヘルプファイルがchdirについて言うように動作します:* TRUEでfileがパス名の場合、R作業ディレクトリは一時的に変更されます*評価のためのファイルを含むディレクトリに移動します。*エラーメッセージは、Rが現在の作業ディレクトリ内のscript.Rという名前のファイルを見つけることができないことを示します。 –
lmo
私のファイル名はlpp.Rです。私はこの名前をつけています...私はRStudioの他のバージョンで親フレームで簡単にそれをやったことを覚えています。 –
Rスタジオのプロジェクトフォルダでは、すべてのファイルパスがプロジェクトのルートディレクトリを基準にしていると仮定することをお勧めします。 [作業ディレクトリの不具合を停止する](https://gist.github.com/jennybc/362f52446fe1ebc4c49f)を参照してください。私は個人的には使用しませんが、[here](https://krlmlr.github.io/here/)パッケージは、指定されたファイルの場所を見つけるのにおすすめです。 –