R 中是否有类似于 Python 的 % 的字符串格式化运算符?

新手上路,请多包涵

我有一个 url,我需要发送请求以使用日期变量。 https 地址采用日期变量。我想使用 Python 中的格式化运算符 % 之类的方法将日期分配给地址字符串。 R 是否有类似的运算符,或者我是否需要依赖 paste()?

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

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

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

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

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

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

有更好的方法吗?

原文由 Conner M. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 693
2 个回答

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"

原文由 LyzandeR 发布,翻译遵循 CC BY-SA 3.0 许可协议

作为 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

原文由 austensen 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题