I use ggplot2 to study the effects of various military operations on killings. To show the effect, I draw a vertical line when the operation took place, and a smooth line of the kill level before and after the operation.
I wrote a facet_wrap chart to show this for a whole group of counties. It works beautifully, but when converting to a function, I get an error when using a local variable to draw a vertical line.
Here is a sample code:
drawTS <- function(df, dates, text) { p <- ggplot(df, aes(date, murders)) + facet_wrap(~ county, ncol = 1, scale="free_y") + scale_x_date() + geom_smooth(aes(group = group), se = FALSE) for(i in 1:length(dates)) {
There is no error in a global variable, but it looks ugly.
If instead of the variable temp[i] I use dates[i] inside geom_vline() , I get the following:
Error in NextMethod ("["): object 'i' not found
If I wrap the dates[i] variable in aes() , I get:
Error in eval (expr, envir, enc): 'county' object not found
Does anyone know how to fix this?
source share