`With` use inside a function (wrapper)

I would like to write a wrapper around the user-defined function that takes some vectors as input (eg mtcars$hp, mtcars$ametc.) to enter the input as the name of the data frame (as a parameter data, for example mtcars) and variable names (eg: hpand am), as usual in most standard functions.

But I have some problems, my suggested function is "demo" (wrapping around meandoes not work.

the code:

f <- function(x, data=NULL) {
    if (!missing(data)) {
        with(data, mean(x))
    } else {
        mean(x)
    }
}

Running against vector works, of course:

> f(mtcars$hp)
[1] 146.69

But withunsuccessfully unsuccessful:

> f(hp, mtcars)
Error in with(d, mean(x)) : object 'hp' not found

In a global environment / without my user function it works correctly:

> with(mtcars, mean(hp))
[1] 146.69

substitute, deparse , - . !

+5
3

:

f <- function(x,data=NULL) {
  eval(match.call()$x,data) # this is mtcars$hp, so just take the mean of it or whatever
}

> f(hp,mtcars)
 [1] 110 110  93 110 175 105 245  62  95 123 123 180 180 180 205 215 230  66  52  65  97 150 150 245 175  66
[27]  91 113 264 175 335 109

# it even works without a data.frame specified:
> f(seq(10))
 [1]  1  2  3  4  5  6  7  8  9 10

. @Andrie @Hadley , . . @Hadley : f() .

R (, , ). , hp, , -. match.call , .

eval . ?eval, :

, expr . NULL, a , , , sys.call.

, NULL ( data.frame) data.frame.

, ( x ):

> g <- function(x) {
+   0
+ }
> g(hp)
[1] 0
+10
f <- function(x, data=NULL) {
    if (!missing(data)) { colname=deparse(substitute(x))
         mean(data[[colname]])
    } else {
        mean(x)
    }
}

 f(hp, mtcars)
[1] 146.6875

( , , @gsk, , . ', , .)

+3

:

f <- function(x, data = NULL) {
     if (is.null(data)) {
         mean(x)
     } else { 
         attach(data)
         mean(x)
         detach(data)
     }
 }

. f (hp, mtcars)

-1

All Articles