我正在使用Rscript绘制某个目录中给定CSV文件中的一些数字,这不一定是我当前的工作目录.我可以这样称呼它:
./script.r ../some_directory/inputfile.csv
Run Code Online (Sandbox Code Playgroud)
现在我想在同一目录(../some_directory)中输出我的数字,但我不知道该怎么做.我试图获取输入文件的绝对路径,因为从这里我可以构造输出路径,但我无法找到如何做到这一点.
Mat*_*agg 46
normalizePath() #Converts file paths to canonical user-understandable form
Run Code Online (Sandbox Code Playgroud)
要么
library(tools)
file_path_as_absolute()
Run Code Online (Sandbox Code Playgroud)
这里是解决方案:
args = commandArgs(TRUE)
results_file = args[1]
output_path = dirname(normalizePath(results_file))
Run Code Online (Sandbox Code Playgroud)
这个问题很老,但是仍然错过了一个可行的解决方案。所以这是我的答案:
使用normalizePath(dirname(f))。下面的示例列出了当前目录中的所有文件和目录。
dir <- "."
allFiles <- list.files(dir)
for(f in allFiles){
print(paste(normalizePath(dirname(f)), fsep = .Platform$file.sep, f, sep = ""))
}
Run Code Online (Sandbox Code Playgroud)
哪里:
normalizePath(dirname(f))给出父目录的绝对路径。因此,应将各个文件名添加到路径中。.Platform用于具有操作系统可移植的代码。(这里)file.sep给出“在您的平台上使用的文件分隔符:在Unix-like和Windows上均使用“ /”(但在以前的Classic Mac OS上没有)。(这里)警告:如果不谨慎使用,可能会引起一些问题。例如,假设这是路径:A/B/a_file并且工作目录现在设置为B。然后下面的代码:
dir <- "B"
allFiles <- list.files(dir)
for(f in allFiles){
print(paste(normalizePath(dirname(f)), fsep = .Platform$file.sep, f, sep = ""))
}
Run Code Online (Sandbox Code Playgroud)
会给:
> A/a_file
Run Code Online (Sandbox Code Playgroud)
但是,应该是:
> A/B/a_file
Run Code Online (Sandbox Code Playgroud)