【问题标题】:Evaluating ddply within a function when passed ggplot2 aesthetic mappings as arguments将 ggplot2 美学映射作为参数传递时在函数内评估 ddply
【发布时间】:2013-08-07 19:57:56
【问题描述】:

我正在开发一个在 ggplot2 中创建 bean 图的函数,并且一直停留在计算每个组的中位数的步骤上。我在Object not found error with ddply inside a functionObject not found error with ddply inside a function 尝试了一些解决方案,但仍然无法正常工作。返回的错误消息是"Error in as.quoted(.variables) : object 'iv' not found",这表明它没有评估 符号iv 在正确的环境中。如果可能的话,我想保留使用 ggplot2 美学映射将变量传递给函数的方法,因为 稍后我将在函数中为小提琴和地毯图使用相同的美学映射。

函数代码:

 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)

}

样本数据

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

使用 ggplot2 美学调用函数

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

应该提供类似的东西

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

【问题讨论】:

    标签: r plyr


    【解决方案1】:

    如果您尽早“渲染”美学,您会发现生活更轻松。那么你就不需要任何特殊的 ddply 调用了:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-21
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多