I'm interested in Using functions and lapply to make properly labelled histograms.
But when I try to use a function and lapply to create histograms that display the spread of data, the xlab doesn't give the text of the variable of interest. Instead it uses the first value of the variable of interest. How to I fix this issue?
The code I used is below:
# loads ggplot2 package
if(!require(ggplot2)){install.packages("ggplot2")} # ---- NOTE: relates to mlm analyses
# creates function_dataset_diamonds_DV_histogram
function_dataset_diamonds_DV_histogram <-
function(
DV_use
)
{
ggplot(diamonds, aes(x=as.numeric(DV_use))) +
geom_histogram(aes(y=..density..), alpha=0.5,
position="identity", binwidth = nclass.Sturges(DV_use)) +
geom_density(alpha=.2) +
theme(legend.position="right") +
xlab(DV_use)
}
# tests function
function_dataset_diamonds_DV_histogram(diamonds$carat)
# applies function
lapply((diamonds[c(1,8:10)]), function_dataset_diamonds_DV_histogram)