I want to plot Histograms for a number of continuous variables from different data sets. I created a function for a ggplot histogram:
library(ggplot2)
# two parameters
FU <- function(dat, var){
ggplot(data = dat, aes_string(var)) +
geom_histogram(aes(y=..density..), bins = 20)}
FU(diamonds, "y")
Now I defined a list that includes my continuous variables and wanted to apply this to the diamonds data set:
vars <- list("x", "y")
lst <- mapply(FU, diamonds, vars)
But this gives me th following error:
Error: ggplot2 doesn't know how to deal with data of class numeric
mapply
applies FUN to the first elements of each ... argument.Consequently, mapply will take as input the first element of diamonds.
When looking at length(diamonds) we can see that diamonds has 10 elements (10 variables).
So the current code apply the function to each variable of diamonds for each elements of the list
c("x", "y")
To correctly do this, I fear that using a for loop is in that case relevant, at least for the dataset.