Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

Is there a string formatting operator in R similar to Python's %?

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"

This is what I would do in Python 2.7:

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

Or using .format() in 3.+.

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) 

Is there a better way of doing this?

question from:https://stackoverflow.com/questions/46085274/is-there-a-string-formatting-operator-in-r-similar-to-pythons

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The equivalent in R is 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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...