1

In PHP I can use the dot to paste strings:

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

How can I do something similar in R?

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

seems like a lot of extra typing for such a simple task.

  • 2
    You can save some typing with `paste0(path, "file.txt")`. – juba May 28 '13 at 08:54
  • Nice. Why don't you give that as an answer so I can accept it? –  May 28 '13 at 08:56
  • Ok, I added an answer. – juba May 28 '13 at 09:04
  • Not a duplicate, because I don't want to be restricted to only two strings. –  May 28 '13 at 12:03
  • 8
    Are you telling me you haven't even looked at the documentation for paste? There is no restriction - just add more stuff into paste. `paste("Seriously", "give", "it", "a", "try...")` – Dason May 28 '13 at 12:16

5 Answers5

6

You can also use file.path which Construct the path to a file from components in a platform-independent way.

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

file.path(path,file)
agstudy
  • 119,832
  • 17
  • 199
  • 261
4

In recent R versions, you can save some typing with :

paste0(path, "file.txt")

paste0(...) is equivalent to paste(..., sep=""), and slightly more efficient.

juba
  • 47,631
  • 14
  • 113
  • 118
4

You should really use file.path and paste since it's fast and platform independent. (seealso tools::file_ext, tools::file_path_sans_ext), but below is a little function that is intended for Linux or Mac systems that might come in handy. I don't use it very often because if I share my code, I either have to give the user this function or a personal package that contains it, so I usually end up editing the code to use file.path and it turns out to be less work to just not use this function to begin with.

> 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
}
GSee
  • 48,880
  • 13
  • 125
  • 145
3

If you want things to look a lot like PHP you can define your own infix operator and set it equal to paste():

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

Of course you could use paste0 instead if you wanted concatenated rather than space-separated strings.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
2

Or as an alternative to paste0:

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

for more entries in a string, @BenBolker suggested:

sprintf("%s/%s.%s", path, file, extension)
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149