(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"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…