Skip to content

call lattice function in a function passing "groups" argument

3 messages · Thomas Zumbrunn, Ryan, Deepayan Sarkar

#
I'm trying to use a lattice function within a function and have problems 
passing the "groups" argument properly. Let's say I have a data frame

d <- data.frame(x = rnorm(100), y = c("a", "b"))

and want to plot variable x in a densityplot, grouped by the variable y, then 
I would do something like

densityplot(~ x, d, groups = y)

If however I wanted to call the function "densityplot" within a function and 
pass the "groups" argument as an argument of that function, how would I have 
to proceed? It is not as straightforward as

f <- function(data, groupvar) {
  densityplot(~ x, data, groups = groupvar)
}

probably because the lattice function "densityplot.formula" preprocesses 
the "groups" argument with

groups <- eval(substitute(groups), data, environment(formula))

It there a way how I could pass the "groups" argument in the function "f"?

Thanks for any hints,
Thomas Zumbrunn
#
Here's one approach.  Pass the 'groups' variable as a character, then find 
that variable in the data frame and rename it.

d <- data.frame(x = rnorm(100), y = c("a", "b"))

f <- function(data, groupvar) {
	names(data)[which(names(data) == groupvar)] <- "gp"
  	densityplot(~ x, data, groups = gp)
}

f(d, groupvar="y")
#
On Thu, Dec 11, 2008 at 2:55 AM, Thomas Zumbrunn <t.zumbrunn at unibas.ch> wrote:
Yes, that's the price of non-standard evaluation.
The obvious solution is to evaluate 'groupvar' yourself:

f <- function(data, groupvar) {
  groupvar <- eval(substitute(groupvar), data, parent.frame())
  densityplot(~ x, data, groups = groupvar)
}

A more general solution (where 'groupvar' may be missing) is to use
match.call() etc. (e.g., see lattice:::dotplot.formula)

-Deepayan