2017-10-31 23 views
7

現在のスクリプトのパスに作業ディレクトリをプログラムで設定したいのですが、まず現在のスクリプトのパスを取得する必要があります。 RStudioメニューはありません
現在のスクリプトのパスを取得

current_path = ...retrieve the path of current script ... 
setwd(current_path) 

と同じように: RStudio set working directory

は、これまでのところ、私が試した:

は、だから私は行うことができるようにしたいと思い

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

また、私はherehereherehereからすべての答えを見ました。 喜びはありません。あなただけのディレクトリをしたい場合はRStudioでRStudio 1.1.383

EDIT: It would be great if there was no need for an external library to achieve this.

+0

おそらく 'source(" /script.R "、chdir = TRUE)'は、ヘルプファイルがchdirについて言うように動作します:* TRUEでfileがパス名の場合、R作業ディレクトリは一時的に変更されます*評価のためのファイルを含むディレクトリに移動します。*エラーメッセージは、Rが現在の作業ディレクトリ内のscript.Rという名前のファイルを見つけることができないことを示します。 – lmo

+0

私のファイル名はlpp.Rです。私はこの名前をつけています...私はRStudioの他のバージョンで親フレームで簡単にそれをやったことを覚えています。 –

+0

Rスタジオのプロジェクトフォルダでは、すべてのファイルパスがプロジェクトのルートディレクトリを基準にしていると仮定することをお勧めします。 [作業ディレクトリの不具合を停止する](https://gist.github.com/jennybc/362f52446fe1ebc4c49f)を参照してください。私は個人的には使用しませんが、[here](https://krlmlr.github.io/here/)パッケージは、指定されたファイルの場所を見つけるのにおすすめです。 –

答えて

10

での作業

、あなたは

を使用し、現在

rstudioapi::getSourceEditorContext()$path 

を使用して、ソースペインに表示されるファイルへのパスを取得することができます

dirname(rstudioapi::getSourceEditorContext()$path) 

実行したファイルの名前をにしたい場合は、少し難しいです。変数srcfileをスタックのどこかに戻す必要があります。どこまで戻って、あなたが物事を書く方法によって異なりますが、それは周りの4つのステップバックです:例えば、

fi <- tempfile() 
writeLines("f()", fi) 
f <- function() print(sys.frame(-4)$srcfile) 
source(fi) 
fi 

は、最後の2行で同じことを印刷する必要があります。

+0

これは素晴らしいです。良いことは、 'here'パッケージよりも依存性が少ないことです。真実は私が図書館なしでこれをすることを望んでいたことです。誰かが何かを加えているかどうかを確認するために1/2日待ってから、それを受け入れます。ありがとう。 –

+0

私はちょうどオフィスの別のPCにクリーンインストールを行いました。最新のRスタジオ( '1.1.383')、最新のRバージョン(' Rバージョン3.4.2(2017-09-28) ')今すぐこのエラーが表示されます: 'エラー: 'getSourceEditorContext'は 'namespace:rstudioapi''からエクスポートされたオブジェクトではありません –

+0

' rstudioapi'のどのバージョンを使用していますか? 0.7はCRAN上の最新ですが、かなり最近です。 – user2554330

5

hereパッケージをインストールし、Ode to the here packageを読んでください。 here()機能の

install.packages("here") 
library(here) 
here() 

ドキュメント:

Starting with the current working directory during package load time, here will walk the directory hierarchy upwards until it finds a directory that satisfies at least one of the following conditions:

  • contains a file matching [.]Rproj$ with contents matching ^Version: in the first line
  • [... other options ...]
  • contains a directory .git

Once established, the root directory doesn't change during the active R session. here() then appends the arguments to the root directory.

here package is available on githubの開発バージョン。

+0

Paulは素晴らしい作品です。私はCranバージョン '0.1'からダウンロードします。 –

+0

ありがとう@PanosKal。 CRANから簡単にインストール命令を更新しました。 –

関連する問題