R中的字符串格式化运算符是否与Python的%相似?

Con*_* M. 21 python string format r

我有一个网址,我需要发送使用日期变量的请求.https地址采用日期变量.我想使用像Python中的格式化运算符%那样将日期分配给地址字符串.R有一个类似的运算符还是我需要依赖paste()?

# Example variables
year = "2008"
mnth = "1"
day = "31"
Run Code Online (Sandbox Code Playgroud)

这就是我在Python 2.7中要做的事情:

url = "https:.../KBOS/%s/%s/%s/DailyHistory.html" % (year, mnth, day)
Run Code Online (Sandbox Code Playgroud)

或者在3. +中使用.format().

我唯一知道在R中做的事情似乎很冗长并且依赖于粘贴:

url_start = "https:.../KBOS/"
url_end = "/DailyHistory.html"
paste(url_start, year, "/", mnth, "/", day, url_end) 
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法呢?

Lyz*_*deR 32

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"
Run Code Online (Sandbox Code Playgroud)

此外,虽然我认为这是一种矫枉过正,但您也可以自己定义一个操作员.

`%--%` <- 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"
Run Code Online (Sandbox Code Playgroud)

  • 也许还值得展示一个例子,说明像"https:.../KBOS /%s /%s /%s/DailyHistory.html"% - %list(1999:2000,mnth,day)`或sprintf这样的矢量化当量.(我想在python中他们会循环这种东西.) (3认同)

aus*_*sen 22

作为替代方案sprintf,您可能想要查看glue.

更新:stringr 1.2.0中,他们添加了一个包装函数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
Run Code Online (Sandbox Code Playgroud)


Uwe*_*Uwe 6

stringr包具有以下str_interp()功能:

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

或使用列表(请注意,现在传递数值):

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

顺便说一句,格式化指令也可以传递,例如,如果月份字段需要两个字符宽:

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