【发布时间】:2016-05-06 14:54:14
【问题描述】:
我想将当前文件位置作为工作目录。
使用 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 setting working directory to source file location?
R command for setting working directory to source file location
get filename and path of `source`d file
setwd() in the current working dir
Command for "Set working directory to source file location"
SublimeText and R: Setting Current File Directory
@987654327 @
What is a fool-proof way of permanently setting R working directory?
R setting working directory to source file location?
How to get into the directory of a file in R?
【问题讨论】:
-
什么是
class(parent.frame(2)$ofile)? -
@MichaelChirico 我不知道,我听从了链接stackoverflow.com/questions/34843889/…的建议
-
添加行
print(class(parent.frame(2)$ofile))并尝试运行您的函数。l -
@MichaelChirico 的答案是“NULL”
-
为了澄清,这里的所有方法只适用于
sourced 或传递给RScript的文件。似乎无法确定当前逐行运行的文件(或该文件的目录)(Ctrl+R)。 R应该怎么知道?在这种情况下,代码逐行传递给解释器——不涉及文件。但是,RStudio 知道哪个文件当前处于活动状态,但恕我直言,目前没有办法利用它。