[R] how to pass "arguments" to a function within a function?

jim holtman
2007-05-11T00:50:08Z

You weren't passing in any 'x' and 'y' arguments to the
'fun'.

Try this:

vars.in = data.frame(x='sample1',y='sample2')


examplefun  <- function(fun, vars=vars.in, ...) {

       for(v in 1: ncol(vars) ) {
           assign( names(vars)[v]  , vars[1,v]  , env=.GlobalEnv)
       }
       fun(x=as.character(vars[1,1]), y=as.character(vars[1,2]))
}

examplefun(fun=minus, vars = vars.in)


On 5/10/07, new ruser <newruser at yahoo.com>
wrote:
> I have searched the r-help files but have not been able to find an answer
to this question.  I apologize if this questions has been asked previously.
>
> (Please excuse the ludicrousness of this example, as I have simplified my
task for the purposes of this help inquiry.  Please trust me that something like
this will in fact be useful what I am trying to accomplish. I am using R 2.4.1
in Windows XP.)
>
> I have created two functions:
>
> 1. minus <- function(x,y) {get(x)-get(y)}
>
> a. note: x and y are of type character and represent the names of numerical
objects)
>
>
> 2. examplefun  <- function(fun, vars=vars.in, ...) {
>
>        for(v in 1: ncol(vars) ) {
>            assign( names(vars)[v]  , vars[1,v]  , env=.GlobalEnv)
>                                        }
>
> fun(...) }
>
> a. FUN = another function (e.g. minus() that takes as its inputs variables
of type chatrcater
> b. vars = (a data.frame with the names of variables that will be passed to
"FUN"
>
> My problem: various inputs for "FUN" will require different
arguments.  These arguments will be contained in the column names of
"vars".  How do I pass these arguments to FUN()?
>
>
> My example and my attempt:
>
> what I am trying to do, successfully accomplished without a function:
> x='sample1'
> y='sample2'
>
> sample1=c(222,333,444)
> sample2=c(100,200,300)
>
> minus <- function(x,y) {get(x)-get(y)}
> minus(x,y)
>
> #########################################################
>
> #My so-far failing attempt to write a function to do the same thing:
>
> vars.in = data.frame(x='sample1',y='sample2')
>
>
> examplefun  <- function(fun, vars=vars.in, ...) {
>
>        for(v in 1: ncol(vars) ) {
>            assign( names(vars)[v]  , vars[1,v]  , env=.GlobalEnv)
>                                        }
>
> fun(...) }
>
> examplefun(fun=minus, vars = vars.in)
>
>
> ---------------------------------
> Now that's room service! Choose from over 150,000 hotels
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.
>


--
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?