gpt4 book ai didi

r - ggplot2:stat_summary 在尝试将函数参数作为参数传递时抛出错误,而不是硬编码

转载 作者:行者123 更新时间:2023-12-04 21:10:26 28 4
gpt4 key购买 nike

当我尝试将参数传递到 round 时出现错误内函数stat_summary (即使类似的代码适用于,比如说, geom_text )。下面是一个例子:

# Fake data
set.seed(5)
dat = data.frame(group=rep(c("A","B"),each=10), val=rnorm(20))

我们将尝试使用参数设置值标签的小数位数,而不是对其进行硬编码:
places = 2

ggplot(dat, aes(group, val)) +
stat_summary(fun.y=mean, geom="text", aes(label=round(..y.., places)))

Error in eval(expr, envir, enclos) : object 'places' not found



但是,以下两个示例工作正常。
ggplot(dat, aes(group, val)) +
stat_summary(fun.y=mean, geom="text", aes(label=round(..y.., 2)))

ggplot(dat, aes(group, val)) +
geom_text(aes(label=round(val, places)))

我在尝试编写 ggplot 函数时遇到了这个问题。起初我认为问题涉及 ggplot 没有从函数环境中获取参数,但上面的例子表明这不是问题。为完整起见,以下是该函数的简化示例以及错误消息。如果我将数字参数硬编码为 round,该函数工作正常,而不是试图通过 places范围。
pp1 = function(data, group, var, places=2, e=1.5) {

ggplot(data, aes_string(group, var)) +
geom_boxplot() +
stat_summary(fun.y=mean, geom="text", aes(label=round(..y.., places))) +
scale_y_continuous(limits = e * range(data[,var]))

}

pp1(dat, "group","val")

Error in eval(expr, envir, enclos) : object 'places' not found



我希望找出我是否做错了什么以及如何获得所需的行为。

我在运行 R 3.2.3 和 ggplot2 OS X 10.10.5 上的 2.1.0。

最佳答案

aes用途 non-standard evaluation ,因此将尝试评估 placesdata你给它的论据。但是,它的 NSE 会有所不同,具体取决于您通过它的内容。

绕过 NSE 的典型方法是使用 substitute ,它替换了代码内部的值。然后您可以使用 eval运行代码:

eval(substitute(ggplot(dat, aes(group, val)) +
stat_summary(fun.y=mean, geom="text", aes(label=round(..y.., places))),
list(places = places)))

它按预期工作:

plot with labels

Hadley 还提供了 aes 的几个 SE 版本: aes_ , aes_q , 和 aes_string ,这可能会让您避免使用 substitute ,但我无法评估 ..y.. . (如果有人知道如何构建它,请发表评论,我会更新。)

Hadley 还创建了 lazyeval package ,这对于管理 NSE 很有用。

关于r - ggplot2:stat_summary 在尝试将函数参数作为参数传递时抛出错误,而不是硬编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35806038/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com