我想将当前文件位置作为工作目录。
使用 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")
在 ~/.Rprofile 中为 Rstudio 使用函数(有效!):,
##############################################
# 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中的文件目录?