如何在R中获取执行脚本的目录?

时间:2018-03-09 15:10:07

标签: r

我有一个看起来像这样的函数:

test_X = pca.transform(test_1)

我想要实现的是,给定一个文件名,我想搜索该文件名是否在read_data <- function(filename, header) { path <- paste("./output/", filename, sep = "") if (file.exists(path)) { data <- read.csv(file = path, header = header, sep = ",") } # Partially removed for brevity. } 子目录中可用,该子目录是我的脚本所在的子目录,如果它可用,我想要阅读该文件。问题是,只要我知道output函数的文件参数需要文件的完整路径。所以,我不知何故需要获取我的脚本所在的目录,因此我可以将其与子目录和文件名的其余部分连接起来。我可以使用read.csv获取当前的工作目录,但这并不完全相同,因为我的工作目录似乎总是被修复,而脚本可以位于计算机的任何位置。任何想法如何获取脚本的目录,并将其与输出子目录和R中提供的文件名连接?

4 个答案:

答案 0 :(得分:1)

如果你想确定执行脚本的目录,这可能是一个重复:Rscript: Determine path of the executing script

initial.options <- commandArgs(trailingOnly = FALSE)
file.arg.name <- "--file="
script.name <- sub(file.arg.name, "", initial.options[grep(file.arg.name, initial.options)])
script.dirname <- dirname(script.name)
print(script.dirname)

答案 1 :(得分:0)

添加这个作为你的答案修补。

考虑到你只是想读取一个文件,你可以这样做:

## So what does this do?
# The path is where the files exist
# The pattern is some identifiable portion of the file name, which list.files() will bring back
# You need the full name so that R knows where to read from, this way you don't have to set a new working directory.


data <- if(file.exists(list.files(path = "./output/", pattern = "filename",full.names=T))){ read.csv(list.files(path = "./output/", pattern = "filename",full.names=T))}

# Let's imagine you have a number of files to read in

# Generate a list of filenames

filename <- list("file1","file2","file3","filen")

data <- lapply( filename, function(x) {
if( file.exists( list.files( path = "./output/", pattern = x ,full.names=T ) ) ) {
 read.csv( list.files(path = "./output/", pattern = x ,full.names=T) ) }
} )
    # each element of the list is oe of your data files
    data[[1]]
    data[[2]]
    data[[n]]

我不确定你用header声明什么,因为假设csv本身具有标题,另外csv以逗号分隔,因此声明sep字符也是多余的。

答案 2 :(得分:0)

> f <- "/path/to/my/script.R"

> f
[1] "/path/to/my/script.R"

> basename(f)
[1] "script.R"

> dirname(f)
[1] "/path/to/my"

> dirname(dirname(f))
[1] "/path/to"

> file.path(dirname(f), "output")
[1] "/path/to/my/output"

> file.path(dirname(f), "output", "data.csv")
[1] "/path/to/my/output/data.csv"

答案 3 :(得分:0)

从SO中的多个问题中收集资源,我想出了以下解决方案,它似乎适用于多种调用约定:

library(base)
library(rstudioapi)

get_directory <- function() {
  args <- commandArgs(trailingOnly = FALSE)
  file <- "--file="
  rstudio <- "RStudio"

  match <- grep(rstudio, args)
  if (length(match) > 0) {
    return(dirname(rstudioapi::getSourceEditorContext()$path))
  } else {
    match <- grep(file, args)
    if (length(match) > 0) {
      return(dirname(normalizePath(sub(file, "", args[match]))))
    } else {
      return(dirname(normalizePath(sys.frames()[[1]]$ofile)))
    }
  }
}

以后我可以用作:

path <- paste(get_directory(), "/output/", filename, sep = "")