Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

String templates in R

R's {glue} package does what Python's f-strings do. Does R have anything, either in the base language or a package, that does what Python's template strings do?

Python 3 example:

from string import Template
# Define variables in the template string
s = Template('$who likes $what')
# Assign variable values outside of the template string
person = 'tim'
thing = 'kung pao'
s.substitute(who=person, what=thing)
# 'tim likes kung pao'

I found the {templates} package, but it's old, it doesn't seem to be maintained anymore, and there's no git repo or site given so I can submit bug reports or contribute.

Base R's sprintf() doesn't satisfy my requirements.

I know about {reticulate}. I want to know if string templates are possible in R at all, without getting Python involved.

question from:https://stackoverflow.com/questions/65906129/string-templates-in-r

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

1 Answer

0 votes
by (71.8m points)

(1) below addresses the precise syntax in the question while (2) and (3) are variations.

1) gsubfn The gsubfn in the package of the same name with the default pattern (first argument) can do that. It is a superset of gsub where the replacement (second argument) can be a string (like gsub), list, function or proto object. Using $ requires that the string be such that it can detect the end of the word after $ but if not the string can be surrounded by backticks.

The pattern argument (first argument) can be specified if you want different sorts of matches.

library(gsubfn)
gsubfn(, list(who = "person", what = "thing"), '$who likes $what')
## [1] "person likes thing"

2) fn$ There is also fn$ in the same package which is often used with sqldf package but is not specific to it. It allows string interpolation in arguments to a function if the function call is prefaced with fn$ .

who <- "person"; what <- "thing"
fn$c("$who likes $what")
## [1] "person likes thing"

2a) which could be written as shown to limit the scope of who and what.

local({
  who <- "person"; what <- "thing"
  fn$c("$who likes $what")
})
## [1] "person likes thing"

3) sprintf The base of R supports sprintf which is positional rather than keyword oriented:

sprintf("%s likes %s", "person", "thing")
## [1] "person likes thing"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...