R中是否有类似于Python%的字符串格式运算符? [英] Is there a string formatting operator in R similar to Python's %?

查看:128
本文介绍了R中是否有类似于Python%的字符串格式运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a url that I need to send a request to using date variables. The https address takes the date variables. I'd like to assign the dates to the address string 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"

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

This is what I would do in Python 2.7:

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

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

Or using .format() in 3.+.

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

The only I'd know to do in R seems verbose and relies on paste:

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

有更好的方法吗?

推荐答案

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"

此外,尽管我认为这太过分了,但您也可以自己定义一个运算符.

Also, although I think it is an overkill, you could define an operator yourself too.

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

这篇关于R中是否有类似于Python%的字符串格式运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆