0

I'm working on a function to create bean plots in ggplot2 and am stuck on the step calculating medians for each group. I've tried a couple of the solutions at Object not found error with ddply inside a function and Object not found error with ddply inside a function but was still unable to get it to work. The error message returned is "Error in as.quoted(.variables) : object 'iv' not found" which indicates it's not evaluting the symbol iv in the correct environment. If possible, I would like to keep the method of passing the variables to the function with ggplot2 aesthetic mapping since I will be using the same aesthetic mappings for the violin and rug plots later on in the function.

The code for the function:

 ggbean <- function(data = NULL, mapping = NULL, ...){
  require(plyr)

  x <- mapping[['x']]
  y <- mapping[['y']]

# Calculate medians for each group
 medFn <- function(mydat, x1, y1){
    z <- do.call("ddply",list(mydat, x1, summarize, med = call("median", y1, na.rm=TRUE)))
    return(z)
 }

res <- medFn(data, x, y)

}

Sample data

set.seed(1234)
single_df <- data.frame(dv = c(rnorm(100), rnorm(100,12,3)), 
iv = as.factor(sample(LETTERS[1:4], size = 200, replace = TRUE)))

Call to function with ggplot2 aesthetics

res3 <- ggbean(data = single_df, aes(x = iv, y = dv))

should provide something like

  iv      med
  1  A 7.254916
  2  B 1.367827
  3  C 1.467737
  4  D 8.670698
Community
  • 1
  • 1

1 Answers1

2

You'll find life easier if you "render" the aesthetics early on. Then you don't need any special ddply calls:

library(ggplot2)
library(plyr)

ggbean <- function(data, mapping, ...) {
  df <- quickdf(eval.quoted(mapping, data))
  ddply(df, "x", summarise, med = median(y, na.rm = TRUE))
}

single_df <- data.frame(
  dv = c(rnorm(100), rnorm(100, 12, 3)), 
  iv = sample(LETTERS[1:4], size = 200, replace = TRUE)
)

res3 <- ggbean(data = single_df, aes(x = iv, y = dv))
hadley
  • 102,019
  • 32
  • 183
  • 245