[R] how to pass user input to a function?
Don MacQueen
macq at llnl.gov
Tue Aug 25 20:15:46 CEST 2009
And an alternative to nested if else's, in a case where they are
actually needed, is
switch
-Don
At 1:06 PM -0400 8/25/09, Ista Zahn wrote:
>Nice one Gabor! It works great, and is really simple. Bill Dunlap's
>solution of
>
>GET$pass.var <- as.name(GET$pass.var)
>eval(substitute(mean(x), list(x=GET$pass.var)))
>
>also works.
>
>Thanks!
>
>
>On Tue, Aug 25, 2009 at 12:59 PM, Gabor
>Grothendieck<ggrothendieck at gmail.com> wrote:
>> Try this:
>>
>> x <- get(GET$pass.var)
>> mean(x)
>>
>>
>> On Tue, Aug 25, 2009 at 12:26 PM, Ista
>>Zahn<izahn at psych.rochester.edu> wrote:
>>> Hi everyone,
>>> I'm building a website (http://*yourpsyche.org) using Jeffrey Horner's
>>> awesome Rapache module. I want to take user input, and pass it to an R
>>> script. At first I was simply using if else statements, but after a
>>> while I had so many nested if else's in my code that my head was
>>> spinning. So then I started using cat() and source() to write
>>> temporary files and read them back in (see example below). I've
>>> searched around, and I think there might be a better way to do it with
>>> substitute(), but I can't seem to figure it out (see attempt below).
>>>
>>> Here is a minimal example:
>>>
>>>> ###set up simple example###
>>>> GET <- list(pass.var="b")
>>>> a <- 1:10
>>>> b <- 11:20
>>>>
>>>> ###using if else works but becomes confusing when I have a lot
>>>>of variables to pass###
>>>> if(GET$pass.var=="a")
>>> + {
>>> + mean(a)
>>> + } else if(GET$pass.var=="b")
>>> + {
>>> + mean(b)
>>> + }
>>> [1] 15.5
>>>>
>>>> ###writing to a temporary file works but feels like a hack and
>>>>results in many temp
> >> files###
> >>> cat('print(mean(', GET$pass.var,'))', file="tmp.R",sep="")
> >>> source("tmp.R")
> >> [1] 15.5
> >>>
> >>> ###this seems promising but I can't figure it out###
> >>> substitute(mean(x), list(x=GET$pass.var))
>>> mean("b")
>>>>
>>>> ###is there a better way?###
>>>>
>>>
>>> Thanks!
>>> --
>>> Ista Zahn
>>> Graduate student
>>> University of Rochester
>>>
>>> ______________________________________________
>>> 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.
>>>
>>
>
>
>
>--
>Ista Zahn
>Graduate student
>University of Rochester
>
>______________________________________________
>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.
--
--------------------------------------
Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA
925-423-1062
More information about the R-help
mailing list