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

I have a url that should send a request for using date variables. The https address accepts date variables. I would like to assign dates in the address bar 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 thing I know to do in R looks verbose and relies on pasta:

 url_start = "https:.../KBOS/" url_end = "/DailyHistory.html" paste(url_start, year, "/", mnth, "/", day, url_end) 

Is there a better way to do this?

+12
source share
4 answers

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" 

In addition, although I think this is overkill, you can also define an operator.

 `%--%` <- 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" 
+21
source

As an alternative to sprintf you can try glue .

Update: the wrapper function glue::glue() , str_glue() added to stringr 1.2.0


 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 
+13
source

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 numerical values ​​are now 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" 

By the way, formatting directives can also be passed, for example, if the fields of the month must be two characters:

 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" 
+6
source

The simplest, I think, is paste . Example:

 paste("Today is:", Sys.Date()) 

gives:

 [1] "Today is: 2019-01-23" 
0
source

Source: https://habr.com/ru/post/1271585/


All Articles