I would like to write a wrapper around a custom function that takes some vectors as input (like: mtcars$hp
, mtcars$am
etc.) to take input as data frame name (as data
parameter, eg.: mtcars
) and variable names (like: hp
and am
), as usual in most standard function.
But I have some problems, my proposed 'demo' function (a wrapper around mean
does not work.
Code:
f <- function(x, data=NULL) {
if (!missing(data)) {
with(data, mean(x))
} else {
mean(x)
}
}
Running against a vector works of course:
> f(mtcars$hp)
[1] 146.69
But with
fails unfortunatelly:
> f(hp, mtcars)
Error in with(d, mean(x)) : object 'hp' not found
While in global environment/without my custom function works right:
> with(mtcars, mean(hp))
[1] 146.69
I have tried to do some experiment with substitute
, deparse
and others, but without any success. Any hint would be welcomed!
f(hp, mtcars)
? – Respectfulmodel.frame
to get the variables. – Washedupassign(deparse(substitute(x)), x)
inside the function so that the variable could be seen. Is this "wrong"? – Doukhobor