[R] how to pass user input to a function?

Ista Zahn izahn at psych.rochester.edu
Tue Aug 25 19:06:21 CEST 2009


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




More information about the R-help mailing list