Skip to content
Back to formatted view

Raw Message

Message-ID: <loom.20081211T151128-361@post.gmane.org>
Date: 2008-12-11T15:13:57Z
From: Ryan
Subject: call lattice function in a function passing

> 
> 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"?

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")