I have a url that I need to send a request to using date variables. The https address takes the date variables. I'd like to assign the dates to the address string using something like the formatting operator % in Python. Does R have a similar operator or do I need to rely on paste()?
# Example variables
year = "2008"
mnth = "1"
day = "31"
This is what I would do in Python 2.7:
url = "https:.../KBOS/%s/%s/%s/DailyHistory.html" % (year, mnth, day)
Or using .format() in 3.+.
The only I'd know to do in R seems verbose and relies on paste:
url_start = "https:.../KBOS/"
url_end = "/DailyHistory.html"
paste(url_start, year, "/", mnth, "/", day, url_end)
Is there a better way of doing this?
The equivalent in R is
sprintf
:Also, although I think it is an overkill, you could define an operator yourself too.
The
stringr
package has thestr_interp()
function:or using a list (note that now numeric values are passed):
BTW, formatting directives can also be passed, e.g., if the month fields needs to be two characters wide:
As an alternative to
sprintf
, you might want to check outglue
.Update: In stringr 1.2.0 they've added a wrapper function of
glue::glue()
,str_glue()