2017-09-06 48 views
4

我有一個URL,我需要發送一個請求,使用日期變量。 https地址採用日期變量。我想使用類似於Python中的格式化運算符%將日期分配給地址字符串。 R有一個類似的操作符還是我需要依賴paste()?R中是否有類似於Python的%的字符串格式化運算符?

# Example variables 
year = "2008" 
mnth = "1" 
day = "31" 

這是我會做在Python 2.7:在3 +

url = "https:.../KBOS/%s/%s/%s/DailyHistory.html" % (year, mnth, day) 

或者使用.format()。

只有我知道R中做詳細似乎並依賴於貼:

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

是否有這樣做的更好的辦法?

+0

也許例如'paste(url_start,paste(year,mnth,day,sep =「/」),url_end)' – CPak

+0

查看https://stackoverflow.com/questions/17475803/sprintf-format-strings-reference-by-name/17476306#17476306 –

回答

13

R中的等價物是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" 

而且,雖然我認爲這是矯枉過正,你可以自己定義操作了。

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

也許還值得展示一個例子說明向量化像「」https:.../KBOS /% s /%s /%s/DailyHistory.html「% - %list(1999:2000,mnth,day)'或sprintf等價物。 (我猜在Python中,他們會循環這種事情。) – Frank

5

作爲sprintf的替代方法,您可能需要查看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 
2

stringr封裝具有str_interp()功能:

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

或使用列表(注意,現在的數字值傳遞):

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,格式化指令也可以通過,例如,如果月份字段需要寬兩個字:

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"