I am trying to use dplyr within a function to create a user-defined function that I can pass multiple arguments to summarise data with dplyr then plot it with ggplot.
Here is some sample data and what I am trying to do with dplyr then plot
df <-data.frame(Year = c("2006", "2006", "2006", "2007", "2007", "2007", "2008", "2009", "2010", "2010", "2009", "2009"), JudicialOrientation = c("Defense", "Plaintiff", "Plaintiff", "Neutral", "Defense", "Plaintiff", "Defense", "Plaintiff", "Neutral", "Neutral", "Plaintiff","Defense"), Loss = c(100000, 100, 2500, 100000, 25000, 0, 7500, 5200, 900, 100, 0, 50))
df1 <- df %>%
group_by(Year, JudicialOrientation) %>%
summarise(MeanLoss =mean(Loss))
ggplot(df1, aes(x = JudicialOrientation, y = MeanLoss, color = Year, group =Year)) +
geom_line() +
geom_point()
I am now trying to replicate this into a user function so that I can pass different variables to get similar results.
Here is my attempt so far:
ConsistencyPlot <- function(df,var1,timevar,lossvar){
df1 <- df %>%
group_by_(df[timevar], df[var1]) %>%
summarise_(MeanLoss = mean(df[lossvar]))
ggplot(df1, aes(x = var1, y = MeanLoss, color = timevar, group = timevar)) +
geom_line() +
geom_point()
}
ConsistencyPlot(df,"JudicialOrientation","Year",'Loss')
I am replicating the same logic and passing in df
as my dataframe, var1
as the JudicialOrientation
, timevar
as Year
and lossvar
as my vector of Loss
values that I want averaged through summarise
. I cannot get the same results however so I feel like I am missing something with how these functions are used within a closure.