您应该真正使用file.path
andpaste
因为它快速且独立于平台。(另请参阅tools::file_ext
, tools::file_path_sans_ext
),但下面是一个用于 Linux 或 Mac 系统的小功能,可能会派上用场。我不经常使用它,因为如果我共享我的代码,我要么必须给用户这个功能或包含它的个人包,所以我通常最终编辑要使用的代码,file.path
结果证明工作量更少只是不使用此功能开始。
> fpath(path, "filename", extension)
[1] "/path/to/directory/filename.txt"
#' create a filepath
#'
#' This just pastes together \code{dir} and \code{file} and optionally
#' \code{ext}. It is intended for Mac or Linux systems.
#' @param dir character string of directory (with or without trailing slash)
#' @param file character string of filename (with or without extension)
#' @param ext Optional. character file extension. (with or without leading dot)
#' @return character string representing a filepath
#' @examples
#' fpath("path/to", "file", "csv")
#' fpath("path/to/", "file.csv", ".csv")
#' #knows not to duplicatate the "/" or the ".csv"
#' fpath('path/to', 'file.csv')
#' fpath("file", ext="csv") #knows that dir is missing
#' fpath("", "file", "txt") # no leading forward slash if dir == ""
#' @export
fpath <- function(dir, file, ext) {
lchar <- function(x) substr(x, nchar(x), nchar(x)) #last char of string
fl <- if (missing(file)) {
dir
} else {
if (missing(dir) || dir == "") {
file
} else {
dir <- if (substr(dir, nchar(dir), nchar(dir)) != "/") {
paste(dir, "/", sep="")
} else dir
file <- gsub("^/+", "", file) # remove leading forward slashes from file names
paste(dir, file, sep="")
#TODO: should figure out how to throw an error (or allow it to work) if called like
# fpath("ftp:/", "/ftp.domain.com") or fpath('http:/', '/www.domain.com')
}
}
if (lchar(fl) == "/") stop("'file' should not end with a forward slash")
if (!missing(ext)) {
ext <- if (substr(ext, 1, 1) != ".") {
paste(".", ext, sep="")
} else ext
if (substr(fl, nchar(fl) - nchar(ext) + 1, nchar(fl)) != ext) {
fl <- paste(fl, ext, sep="")
}
}
fl
}