我已经在Object not found error with ddply inside a function和Object 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 回答
如果你早期“渲染”美学,你会发现生活更轻松 . 那你就不需要任何特殊的ddply调用了: