Reputation: 1860
I have written a function to create plots, which looks something like this:
getSecPlot <- function(data, xvar, yvar, yvarsec, groupvar, ...){
sec_plot <- ggplot(data, aes_string (x = xvar, group = groupvar)) +
geom_col(aes_string(y = yvar, fill = groupvar, alpha = 0.5), position = "dodge") +
geom_line(aes(y = yvarsec, color = gender))
}
I would like to change this function. Sometimes there is no groupvar. In that case, i woule like to have a plot such as:
sec_plot <- ggplot(data, aes_string (x = xvar, group = 1)) +
geom_col(aes_string(y = yvar), fill = "green") +
geom_line(aes(y = yvarsec, color = gender))
So, i would like to put this together in a single function. Something like:
getSecPlot <- function(data, xvar, yvar, yvarsec, ...){
if (exists groupvar){
sec_plot <- ggplot(data, aes_string (x = xvar, group = groupvar)) +
geom_col(aes_string(y = yvar, fill = groupvar, alpha = 0.5), position = "dodge") +
geom_line(aes(y = yvarsec, color = gender))
} else {
sec_plot <- ggplot(data, aes_string (x = xvar, group = 1)) +
geom_col(aes_string(y = yvar), fill = "green") +
geom_line(aes(y = yvarsec, color = gender))
}
the if (exists groupvar)
is just for illustration - how could i check if the argument has been assigned in R ?
I am unsure about how the ...
works. Once i took the groupvar
out from the functions argument, the function did no longer work:
getSecPlot <- function(data, xvar, yvar, yvarsec, ...){
sec_plot <- ggplot(data, aes_string (x = xvar, group = groupvar)) +
geom_col(aes_string(y = yvar, fill = groupvar, alpha = 0.5), position = "dodge") +
geom_line(aes(y = yvarsec, color = gender))
}
plot.SeverityYearly <- getSecPlot(freqSevDataAge, xvar = "agegroup", yvar = "severity", yvarsec = "frequency", groupvar = "gender")
Error in aes_string(x = xvar, group = groupvar) : object 'groupvar' not found
Upvotes: 0
Views: 50
Reputation: 388982
You can use missing
to check if group_var
is present. See this simple example :
temp <- function(a, b, group_var) {
if(missing(group_var))
a + b
else
a + b + group_var
}
temp(1, 2, 3)
#[1] 6
temp(1, 2)
#[1] 3
Upvotes: 2