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

Gabor Grothendieck ggrothendieck at gmail.com
Tue Aug 25 18:59:46 CEST 2009


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.
>




More information about the R-help mailing list