It seem that I can never get the returned values of 'paste0' been evaluated , as well as any characters that have been quoted. Do I have to use 'substr' or 'gsub' to remove these quotation marks ?
eval(paste0('1','+','1'))
[1] "1+1"
eval(expression(paste0('1','+','1')))
[1] "1+1"
eval(expression("1+1"))
[1] "1+1"
eval("1+1")
[1] "1+1"
eval(expression(1+1))
[1] 2
eval(1+1)
[1] 2
An expression consisting of a string is just the string, evaluating the string just returns the string (if you give R a string at the command line then you will just see the string again). That is why none of your attempts worked (well the did work, they just did not do what you wanted). The quotes are not part of the string, just how it is displayed, so gsub
will not help.
You need to parse the string into an expression, as the comment shows, but be aware of the following:
> library(fortunes)
> fortune(106)
If the answer is parse() you should usually rethink the question.
-- Thomas Lumley
R-help (February 2005)
and
> fortune(181)
Personally I have never regretted trying not to underestimate my own future
stupidity.
-- Greg Snow (explaining why eval(parse(...)) is often suboptimal, answering
a question triggered by the infamous fortune(106))
R-help (January 2007)
Most things that people try to do using paste0
, parse
, and eval
can be done quicker and more simply using other tools. Construction a string, parsing, and evaluating it is kind of like saying that you know a shortcut from Boston to New York and therefore every time you want to go from city A to city B you first go from A to Boston, use your shortcut, then go from New York to B. This may be fine if your going from Rhode Island to New Jersey, but is not very efficient for going between London and Paris. Parsing constructed strings can also lead to difficult to find bugs.
You might consider using functions like bquote
or substitute
:
> eval( bquote( .(a) + .(b), list(a=1, b=2) ) )
[1] 3
Or other more direct tools. If you tell us what you are trying to do then we may be able to suggest better approaches.