Is there a string formatting operator in R similar to Python's %?

Solution 1:

The equivalent in R is sprintf:

year = "2008"
mnth = "1"
day = "31"
url = sprintf("https:.../KBOS/%s/%s/%s/DailyHistory.html", year, mnth, day)
#[1] "https:.../KBOS/2008/1/31/DailyHistory.html"

Also, although I think it is an overkill, you could define an operator yourself too.

`%--%` <- function(x, y) {

  do.call(sprintf, c(list(x), y))

}

"https:.../KBOS/%s/%s/%s/DailyHistory.html" %--% c(year, mnth, day)
#[1] "https:.../KBOS/2008/1/31/DailyHistory.html"

Solution 2:

As an alternative to sprintf, you might want to check out glue.

Update: In stringr 1.2.0 they've added a wrapper function of glue::glue(), str_glue()


library(glue)

year = "2008"
mnth = "1"
day = "31"
url = glue("https:.../KBOS/{year}/{mnth}/{day}/DailyHistory.html")

url

#> https:.../KBOS/2008/1/31/DailyHistory.html

Solution 3:

The stringr package has the str_interp() function:

year = "2008"
mnth = "1"
day = "31"
stringr::str_interp("https:.../KBOS/${year}/${mnth}/${day}/DailyHistory.html")
[1] "https:.../KBOS/2008/1/31/DailyHistory.html"

or using a list (note that now numeric values are passed):

stringr::str_interp("https:.../KBOS/${year}/${mnth}/${day}/DailyHistory.html", 
                            list(year = 2008, mnth = 1, day = 31))
[1] "https:.../KBOS/2008/1/31/DailyHistory.html"

BTW, formatting directives can also be passed, e.g., if the month fields needs to be two characters wide:

stringr::str_interp("https:.../KBOS/${year}/$[02i]{mnth}/${day}/DailyHistory.html", 
                    list(year = 2008, mnth = 1, day = 31))
[1] "https:.../KBOS/2008/01/31/DailyHistory.html"