R:使用 geom_line 访问函数内的列名
R: Access column name within function with geom_line
我有以下使用 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
不幸的是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)
}
)
您可以像使用 x
美学一样使用 aes_string
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)
})
我有以下使用 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
不幸的是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)
}
)
您可以像使用 x
美学一样使用 aes_string
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)
})