首页 文章

在将ggplot2美学映射作为参数传递时,在函数内评估ddply

提问于
浏览
0

我已经在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

1 回答

  • 2

    如果你早期“渲染”美学,你会发现生活更轻松 . 那你就不需要任何特殊的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))
    

相关问题