Pass unevaluated commands to a function in R
I am a bit of an R novice, and I am stuck with what seems like a simple problem, yet touches pretty deep questions about how and when things get evaluated in R.
I am using Rserve quite a bit; the typical syntax to get things evaluated remotely is a bit of a pain to type repeatedly:
RSeval(connection, quote(try(command)))
So I would like a function r which does the same thing with just the call:
r(command)
My first, naive, bound to fail attempt involved:
r <- function(command) {
RSeval(c, quote(try(command)))
}
You've guessed it: this sends, literally, try(command)
to my confused Rserve daemon. I want comma开发者_运维技巧nd
to be partially evaluated, if that makes any sense -- i.e. replaced by what I typed as an argument, but without evaluating it locally.
I looked for solutions to this, browsed throught the documentation for quote, substitute, eval, call, etc.. but I was not able to find something that worked. Either command
gets evaluated locally, or not at all.
This is not a big problem, I can type the whole damn quote(try())
thing all the time; but at this point I am mostly curious as to how to get this to work!
EDIT: More explanations as to what I want to do.
- In the text above,
command
is meant to be a call do a function, ideally -- i.e., not a character string. Something likea <- 3
orassign("a", 3)
rather than"a<-3"
orquote(a<-3)
. I believe that this is part of what makes this tricky. It seems really hard to tell R not to evaluate this locally, but only send it literally. Basically I would like my function to be a bit likequote()
, which does not evaluate its argument. - Some explanation about my intentions. I wish to use Rserve frequently to pass commands to a remote R daemon. The commands would be my own (or my colleagues) and the daemon protected by firewall and authentication (and would not be run as root) -- so there is no worry of malicious commands being passed.
- To be perfectly honest, this is not a big issue, and I would be pretty happy to always use the
RSeval(c, quote(try()))
. At this point I see this more like an interesting inquiry into the subleties of R :-)
You probably want to use the substitute command, it can give you the argument unevaluated that you can build into the call.
I'm not sure if I understood you correctly - would eval(parse(text = command))
do the trick? Notice that command
is a character, so you can easily pass it as a function argument. If I'm getting the point...
Anyway, evaluating user-specified commands is potentially malicious, therefore not recommended. You should either install AppArmor and tweak it (which is not an easy one), or drop the whole evaluation thing...
精彩评论