我有以下使用lapply
生成的图表列表。在函数subset
和aes_string
中,我似乎无法传递对象i
(列名称):
require(ggplot2)
cols <- colnames(mtcars)
lapply(cols[2:length(cols)],
function(i) {
ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
geom_histogram() # +
# geom_vline(aes(xintercept=mean(get(i), na.rm=T)),
# color="red", linetype="dashed", size=1)
}
)
然而,如果我取消注释geom_line
,我会收到以下错误
## Error in get(i) : object 'i' not found
答案 0 :(得分:4)
不幸的是xintercept
无法在aes
中工作,因此该对象在geom_vline
的环境中确实不存在。
您可以将其用作快速修复:
cols <- colnames(mtcars)
lapply(cols[2:length(cols)],
function(i) { Mean = with(mtcars, mean(get(i), na.rm=T));
ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
geom_histogram() +
geom_vline(xintercept=Mean,
color="red", linetype="dashed", size=1)
}
)
答案 1 :(得分:1)
您可以像使用aes_string
美学
x
lapply(cols[2:length(cols)], function(i) {
ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
geom_histogram() +
geom_vline(
aes_string(xintercept = paste0("mean(", i, ", na.rm = TRUE)")),
color = "red", linetype="dashed", size = 1)
})