【问题标题】:How can three or more strings be concatenated in R [duplicate]如何在R中连接三个或更多字符串[重复]
【发布时间】:2013-05-23 04:10:13
【问题描述】:

在 PHP 中我可以使用点来粘贴字符串:

$path = "/path/to/directory/";
$extension =".txt";
$filecounter = $i; // from some loop for creating multiple files
$file = $path . "filename_". $filecounter . $extension;

如何在 R 中做类似的事情?

path <- "/path/to/directory/"
extension <- ".txt"
filecounter <- i
file <- paste(path, paste(paste("filename", $filecounter, sep =""), extension, sep =""), sep ="")

对于这样一个简单的任务,似乎需要大量额外的输入。

【问题讨论】:

  • 您可以使用paste0(path, "file.txt") 节省一些输入。
  • 不错。你为什么不把它作为答案让我接受呢?
  • 好的,我添加了答案。
  • 不是重复的,因为我不想被限制为只有两个字符串。
  • 您是在告诉我您甚至没有查看有关粘贴的文档吗?没有限制 - 只需将更多内容添加到粘贴中。 paste("Seriously", "give", "it", "a", "try...")

标签: r


【解决方案1】:

您还可以使用file.path,它以独立于平台的方式从组件构造文件的路径。

path = "/path/to/directory/"
file = "file.txt"

file.path(path,file)

【讨论】:

  • +1 获得更好的工具
  • 我编辑了我的问题。你能为三个或更多字符串想出一个简单的解决方案,而不仅仅是两个?
  • @what you can replace file in my solution by paste0(filecounter,extension).
【解决方案2】:

在最近的 R 版本中,您可以使用以下命令节省一些输入:

paste0(path, "file.txt")

paste0(...) 等价于paste(..., sep=""),效率稍高。

【讨论】:

  • 我编辑了我的问题。你能为三个或更多字符串想出一个简单的解决方案,而不仅仅是两个?
  • 请看@Dason评论。
【解决方案3】:

您真的应该使用file.pathpaste,因为它速度快且独立于平台。 (另请参阅tools::file_exttools::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
}

【讨论】:

    【解决方案4】:

    如果您希望事情看起来像 PHP 一样 很多,您可以定义自己的中缀运算符并将其设置为等于 paste():

    "%.%" <- paste
    "a" %.% "b" %.% "c" %.% "d"
    ## [1] "a b c d"
    

    当然,如果您想要连接而不是空格分隔的字符串,您可以使用 paste0

    【讨论】:

      【解决方案5】:

      或者作为paste0的替代品:

      sprintf("%s/%s", path, 'file.txt')
      

      对于字符串中的更多条目,@BenBolker 建议:

      sprintf("%s/%s.%s", path, file, extension)
      

      【讨论】:

      • 我编辑了我的问题。你能为三个或更多字符串想出一个简单的解决方案,而不仅仅是两个?
      • sprintf("%s/%s.%s", path, file, extension)
      猜你喜欢
      • 2021-12-13
      • 2015-06-02
      • 1970-01-01
      • 2013-06-28
      • 2015-08-14
      • 2011-11-06
      • 2014-03-15
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多