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

From: Peter Dalgaard <P.Dalgaard_at_biostat.ku.dk>
Date: Fri 05 Jan 2007 - 18:21:34 GMT

Ramon Diaz-Uriarte wrote:
> Dear All,
>
> I've read Thomas Lumley's fortune "If the answer is parse() you should usually
> rethink the question.". But I am not sure it that also applies (and why) to
> other situations (Lumley's comment
> http://tolstoy.newcastle.edu.au/R/help/05/02/12204.html
> 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 = "")))
> calledf(x)
> ## do more stuff
> }
>
>
> Or:
>
> h <- function(x, fpost) {
> calledf <- get(paste("f.", fpost, sep = ""))
> calledf(x)
> ## 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 better?
> Because I can handle differences in argument lists?
>
>
Who says that they are better? If the question is how to call a function specified by half of its name, the answer could well be to use parse(), the point is that you should rethink whether that was really the right question.

Why not instead, e.g.

f <- list("1"=function(x) {x + 1} , "2"=function(x) {x + 2}) h <- function(x, fpost) f[[fpost]](x)

> h(2,"2")
[1] 4
> h(2,"1")

[1] 3

> Thanks,
>
>
> R.
>
>
>
>

-- 
   O__  ---- Peter Dalgaard             ุster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard@biostat.ku.dk)                  FAX: (+45) 35327907

______________________________________________
R-help@stat.math.ethz.ch 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.
Received on Sat Jan 06 11:21:13 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Sat 06 Jan 2007 - 05:30:24 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.