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

Ista Zahn izahn at psych.rochester.edu
Tue Aug 25 18:26:37 CEST 2009


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




More information about the R-help mailing list