Skip to content
Prev 107083 / 398498 Next

eval(parse(text vs. get when accessing a function

On Fri, 5 Jan 2007, Ramon Diaz-Uriarte wrote:

            
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