【发布时间】:2015-07-03 17:46:19
【问题描述】:
问题:为什么我不能在aes() 中调用sapply?
下图的目标:创建显示死亡/活着的比例的直方图,以便组/类型的每个组合的比例总和为 1(示例受之前的 post 启发)。
我知道您可以通过在 ggplot 之外进行总结来得出这个数字,但问题实际上是为什么该函数在 aes 内部不起作用。
## Data
set.seed(999)
dat <- data.frame(group=factor(rep(1:2, 25)),
type=factor(sample(1:2, 50, rep=T)),
died=factor(sample(0:1, 50, rep=T)))
## Setup the figure
p <- ggplot(dat, aes(x=died, group=interaction(group, type), fill=group, alpha=type)) +
theme_bw() +
scale_alpha_discrete(range=c(0.5, 1)) +
ylab("Proportion")
## Proportions, all groups/types together sum to 1 (not wanted)
p + geom_histogram(aes(y=..count../sum(..count..)), position=position_dodge())
## Look at groups
stuff <- ggplot_build(p)
stuff$data[[1]]
## The long way works: proportions by group/type
p + geom_histogram(
aes(y=c(..count..[..group..==1] / sum(..count..[..group..==1]),
..count..[..group..==2] / sum(..count..[..group..==2]),
..count..[..group..==3] / sum(..count..[..group..==3]),
..count..[..group..==4] / sum(..count..[..group..==4]))),
position='dodge'
)
## Why can't I call sapply there?
p + geom_histogram(
aes(y=sapply(unique(..group..), function(g)
..count..[..group..==g] / sum(..count..[..group..==g]))),
position='dodge'
)
get(as.character(FUN), mode = "function", envir = envir) 中的错误: 找不到模式'function'的对象'expr'
【问题讨论】:
-
sapply 通常在 aes 中工作,如以下(愚蠢的)示例所示:
xy <- data.frame(x=1:10,y=1:10) ggplot(xy, aes(x = x, y=sapply(y,mean))) + geom_line()。我的猜测是这与 ..count.. 和 ..group.. 通过 sapply 的作用域有关,或者 ..count.. 和 ..group.. 在 sapply 函数中被 aes 解析的方式有关,但我想不通。