現在のファイルの場所を作業ディレクトリにしたい。
Rstudio の使用 (動作します!):
# Author : Bhishan Poudel
# Program : writehere.r
# Source : Rscript writehere.r
# set working directory here
this.dir <- dirname(parent.frame(2)$ofile) # frame(3) also works.
setwd(this.dir)
# Sample data to test this code
mydata <- seq(1:10)
write.csv(mydata,"writehere.dat")
#This works flawlessly in MacOS 10.9 and Ubuntu 15.1.
端末からのコマンドの使用: Rscript writehere.r (動作しません!)
Error in dirname(parent.frame(2)$ofile) :
a character vector argument expected
Execution halted
------------------
(program exited with code: 1)
端末からのコマンドの使用: Rscript writehere.r (動作するようになりました!)
# Author : Bhishan Poudel
# Program : writehere.r
# Source : Rscript example.r
# set working directory here
this_dir <- function(directory)
setwd( file.path(getwd(), directory) )
# Sample data to test this code
mydata <- seq(1:10)
write.csv(mydata,"writehere.dat")
Rstudio の ~/.Rprofile 内で関数を使用する (動作します!) : ,
##############################################
# inside ~/.Rprofile
# set up working directory
setwd_thisdir <- function () {
this.dir <- dirname(parent.frame(3)$ofile)
setwd(this.dir)
}
##############################################
次に、任意のディレクトリに writehere.r ファイルがあるとします。これで動作します。
# Author : Bhishan Poudel
# Program : writehere.r
# Compile : Rscript writehere.r
# set working directory here
setwd_thisdir
# Sample data to test this code
mydata <- seq(1:10)
write.csv(mydata,"writehere.dat")
質問: なぜ関数
this.dir <- dirname(parent.frame(2)$ofile) # frame(3) also works.
setwd(this.dir)
Rstudio以外のテキストエディタでは動かない?
いくつかの便利なリンクは次のとおりです
。R 作業ディレクトリをソース ファイルの場所に設定しますか?
作業ディレクトリをソース ファイルの場所に設定するための R コマンド現在の作業ディレクトリ内
の `source`d ファイルのファイル名とパスを取得する
setwd()
「作業ディレクトリをソース ファイルの場所に設定する」ためのコマンド
SublimeText と R: 現在のファイル ディレクトリの
設定 作業ディレクトリの設定
R作業ディレクトリを永続的に設定する簡単な方法は何ですか?
R作業ディレクトリをソースファイルの場所に設定しますか?
Rでファイルのディレクトリに入る方法は?