I have the following list of plots generated with lapply. Within functions subset and aes_string I don't seem to have problems passing the object i (the column name):
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)
}
)
And yet if I uncomment geom_line I receive the following error
## Error in get(i) : object 'i' not found
Unfortunately xintercept doesn't work in aes, so the object really doesn't exist in the environment of geom_vline.
You can use this as a quick fix:
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)
}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With