[R] Passing the name of a variable to a function

Liviu Andronic landronimirc at gmail.com
Wed Aug 4 22:24:59 CEST 2010

Dear Anthony

On Wed, 4 Aug 2010 14:56:58 +0100
Anthony Staines <anthony.staines at gmail.com> wrote:
>  What I would like to do is something like "write a function which
> takes the *name* of a variable, presumably a s a character string,
> from a dataframe, as one argument, and the dataframe, as a second
> argument".
I am not sure that this is what you're looking for, but I was working
on this all day and am pretty happy with the result. The following code
takes a list of character variable names x.vars, apply-ies the function
to each variable .var in data frame .data (with optional subset .subs)
and stores the results in a list names-ed after the original
variables list. 

Best regards

my.fun <- function(.var, .data, .subs) {
    res <- list()
    x <- .data[[.var]][.subs]
    res <- bwplot(x, main=.var)

x.vars <- as.list(names(mtcars)[2:5])
names(x.vars) <- names(mtcars)[2:5]
x.vars  ##there's probably a nicer way of doing this

x <- lapply(x.vars, my.fun, .data=mtcars)
x  ##if you use Sweave, don't forget to print(x)

More information about the R-help mailing list