【问题标题】:Is there a string formatting operator in R similar to Python's %?R 中是否有类似于 Python 的 % 的字符串格式化运算符?
【发布时间】:2018-02-15 12:55:05
【问题描述】:

我有一个 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) 

有更好的方法吗?

【问题讨论】:

标签: python r string format


【解决方案1】:

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"

【讨论】:

  • 也许还值得展示一个示例来说明矢量化,例如 "https:.../KBOS/%s/%s/%s/DailyHistory.html" %--% list(1999:2000, mnth, day) 或 sprintf 等价物。 (我猜在 python 中他们会循环这种东西。)
  • 当您的文本中有其他百分比字符时会变得很棘手......例如带有通配符运算符的 SQL 查询。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    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"
    

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

    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"
    

    【讨论】:

    • 这是最接近python中灵活的format的。看起来很不错。
    猜你喜欢
    • 2019-01-02
    • 2021-08-21
    • 2016-03-29
    • 2017-11-29
    • 2011-04-12
    • 2013-08-02
    • 2014-06-20
    • 2023-03-21
    • 2018-01-03
    相关资源
    最近更新 更多