Reputation: 139
I want to define a function that has several histograms as an output. My inputs are: A dataframe, a variable for binwidth and the name of the "x-variable" in Aesthetics. Unfortunately, the code does not work, so I may need to specify the input differently. Can anybody help here? the code is given below:
```
histograms <- function(InputData, my_binwidth, my_xvariable) {
hist_template <- ggplot(aes(x = my_xvariable, y=..density..),
data = InputData) +
geom_histogram(binwidth=my_binwidth)
hist_unscaled <- hist_template +
scale_x_continuous() +
labs(title = "No Scaling")
result <- list(hist_template=hist_template,hist_unscaled=hist_unscaled)
return(result)
}
testhist <- histograms(WineData,0.1,residual.sugar) ```
Upvotes: 0
Views: 477
Reputation: 8110
You can do this if you wrap the variable in rlang
's enquo
function:
library(ggplot2)
library(rlang)
new_histograms <- function(InputData, my_binwidth, my_xvariable) {
var <- rlang::enquo(my_xvariable)
hist_template <- ggplot(aes(x = !!var, y=..density..), data = InputData) +
geom_histogram(binwidth=my_binwidth)
hist_unscaled <- hist_template +scale_x_continuous() +
labs(title = "No Scaling")
result <- list(hist_template=hist_template,hist_unscaled=hist_unscaled)
return(result)
}
mtcars %>% new_histograms(4, cyl)
Upvotes: 1