Is is possible to do something like,
x = function(n,v) paste("<rel name=\"",quote(n),"\" value=\"",quote(v),"\"/>",sep="")
so that x(y,1)
produces,
"<rel name=\"y\" value=\"1\"/>"
of course this doesn't work and instead produces,
"<rel name=\"n\" value=\"v\"/>"
Also I have a nagging feeling that this kind of operation has a technical name, anybody know what it is?
Essentially, it would be nice if I didn't have do x("y","1").
You're looking for substitute
:
x = function(n,v) paste("<rel name=\"",substitute(n),"\" value=\"",
substitute(v),"\"/>",sep="")
x(y,1)
#[1] "<rel name=\"y\" value=\"1\"/>"
Or if you're going to have more complex expressions, deparse(substitute(
:
x = function(n,v) paste("<rel name=\"",deparse(substitute(n)),"\" value=\"",
deparse(substitute(v)),"\"/>",sep="")
x(y + 2, 3)
#[1] "<rel name=\"y + 2\" value=\"3\"/>"
You could use deparse(substitute()
or match.call
. Note I have used sprintf
as I find it easier to decipher than paste
in these situations.
xx <- function(n,v){
x <- sapply(as.list(match.call())[-1],deparse)
sprintf(fmt ='<rel name=\"%s\" value=\"%s\">',x['n'],x['v'])}
xx(y,2)
## [1] "<rel name=\"y\" value=\"2\">"
xx(y, fun(x,b,v))
## [1] "<rel name=\"y\" value=\"fun(x, b, v)\">"
Note that x(y,fun(p;d))
will not parse as it is not a valid R
expression (it won't get past the language intepreter to even start
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.