[R] eval(parse(text vs. get when accessing a function

Bert Gunter gunter.berton at gene.com
Fri Jan 5 19:35:42 CET 2007


Or to add to what Peter Dalgaard said... (perhaps for the case of many more

Why eval(parse())? What's wrong with if then? 

g <- function(fpost,x){if(fpost==1)f.1 else f.2 }(x)

or switch() if you have more than 2 possible arguments? I think your remarks
reinforce the wisdom of Thomas's "axiom" . 

Bert Gunter
Genentech Nonclinical Statistics
South San Francisco, CA 94404

-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Ramon Diaz-Uriarte
Sent: Friday, January 05, 2007 10:02 AM
To: r-help; rdiaz02 at gmail.com
Subject: [R] eval(parse(text vs. get when accessing a function

Dear All,

I've read Thomas Lumley's fortune "If the answer is parse() you should
rethink the question.". But I am not sure it that also applies (and why) to 
other situations (Lumley's comment 
was in reply to accessing a list).

Suppose I have similarly called functions, except for a postfix. E.g.

f.1 <- function(x) {x + 1}
f.2 <- function(x) {x + 2}

And sometimes I want to call f.1 and some other times f.2 inside another 
function. I can either do:

g <- function(x, fpost) {
    calledf <- eval(parse(text = paste("f.", fpost, sep = "")))
    ## do more stuff


h <- function(x, fpost) {
    calledf <- get(paste("f.", fpost, sep = ""))
    ## do more stuff

Two questions:
1) Why is the second better? 

2) By changing g or h I could use "do.call" instead; why would that be
Because I can handle differences in argument lists?



Ramón Díaz-Uriarte
Centro Nacional de Investigaciones Oncológicas (CNIO)
(Spanish National Cancer Center)
Melchor Fernández Almagro, 3
28029 Madrid (Spain)
Fax: +-34-91-224-6972
Phone: +-34-91-224-6900

PGP KeyID: 0xE89B3462

**NOTA DE CONFIDENCIALIDAD** Este correo electrónico, y en s...{{dropped}}

R-help at stat.math.ethz.ch mailing list
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list