0

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").

2 Answers 2

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\"/>"
Sign up to request clarification or add additional context in comments.

2 Comments

The semicolon will be used in almost of values for v. incidentally quote doesn't handle semicolons either.
@csta that's because that's not a valid R expression, as ; signals end of expression, but you haven't closed your parentheses yet; in other words - that will never work, no matter what x is
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.