[R] Evaluate an expresion comming from string

Joshua Wiley jwiley.psych at gmail.com
Thu Sep 1 06:25:50 CEST 2011


Hi ". .",

You are confused about where the quotes come from.  Your character
string does not have double quotes in it---they are just there for
printing.  Compare:

nchar("XXX")
nchar("'XXX'")

for example.  To do what you want, try:

bench <- function(str,...) {
func <- function(x) x+10
  expr <- list(...)[1]
  str <- gsub("XXX",expr,str)
  eval(parse(text = str))
}
bench("func(XXX)", "1")

then avoid using str which is an important function in the utils
package (part of R core/recommended) as a variable name.  Then give
some serious thought about whether you really want to do what you are
doing by cobbling together text you parse and evaluate.  There are
typically simpler, cleaner, more efficient, trustworthy, and generally
more wholesome ways of doing the above (but if you insist,
eval(parse(text = "stuff")) is probably the way to go).

Cheers,

Josh

On Wed, Aug 31, 2011 at 8:12 PM, . . <xkziloj at gmail.com> wrote:
> Whats wrong here?
>
> I was expecting 11 as the result...
>
> Thanks in advance.
>
> bench <- function(str,...) {
> func <- function(x) x+10
>  expr <- list(...)[1]
>  str <- gsub("XXX",expr,str)
>  x <- as.call(gsub("\"","",str))
>  eval(x)
> }
> bench("func(XXX)", "1")
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, ATS Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list