[R] eval(parse(text vs. get when accessing a function
Thomas Lumley
tlumley at u.washington.edu
Sat Jan 6 00:06:14 CET 2007
On Fri, 5 Jan 2007, Ramon Diaz-Uriarte wrote:
> I see, this is direct way of dealing with the problem. However, you first need
> to build the f list, and you might not know about that ahead of time. For
> instance, if I build a function so that the only thing that you need to do to
> use my function g is to call your function "f.something", and then pass
> the "something".
>
> I am still under the impression that, given your answer,
> using "eval(parse(text" is not your preferred way. What are the possible
> problems (if there are any, that is). I guess I am puzzled by "rethink
> whether that was really the right question".
>
There are definitely situations where parse() is necessary or convenient,
or we wouldn't provide it. For example, there are some formula-manipulation problems where it really does seem to be the best solution.
The point of my observation was that it is relatively common for people to ask about parse() solutions to problems, but relatively rare to see them in code by experienced R programmers. The 'rethink the question' point is that a narrowly-posed programming problem may suggest parse() as the answer, when thinking more broadly about what you are trying to do may allow a completely different approach [the example of lists is a common one].
The problem with eval(parse()) is not primarily one of speed. A problem with parse() is than manipulating text strings is easy to mess up, since text has so much less structure than code. A problem with eval() is that it is too powerful -- since it can do anything, it is harder to keep track of what it is doing.
In one sense this is just a style issue, but I still think my comment is good advice. If you find yourself wanting to use parse() it is a good idea to stop and think about whether there is a better way to do it. Often, there is. Sometimes, there isn't.
-thomas
Thomas Lumley Assoc. Professor, Biostatistics
tlumley at u.washington.edu University of Washington, Seattle
More information about the R-help
mailing list