gpt4 book ai didi

R:使用 geom_line 访问函数内的列名

转载 作者:行者123 更新时间:2023-12-01 11:33:40 39 4
gpt4 key购买 nike

我有以下使用 lapply 生成的绘图列表。在函数 subsetaes_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

最佳答案

不幸的是,xinterceptaes 中不起作用,因此该对象在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)

}
)

关于R:使用 geom_line 访问函数内的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29777178/

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