I want to create a density plot for each numerical column of a dataset and then the save the output as the column names.
To preserve data anonymity, I'll use mtcars.
My ideal output would be density plots saved as the following:
mpg.pdf
cyl.pdf
disp.pdf
hp.pdf
drat.pdf
qsec.pdf
vs.pdf
am.pdf
gear.pdf
carb.pdf
My attempt, which obviously doesn't work..
library(dplyr)
library(ggplot2)
col_tmp <- colnames(mtcars)
make_plots <- function(col){
column <- mtcars %>% select(col)
col_plot <- column %>%
ggplot( aes(x=col)) +
geom_density(fill="#69b3a2", color="#e9ecef", alpha=0.8)
ggsave(col_plot, file="col.pdf")
}
lapply(mtcars, make_plots(col_tmp))
I thought maybe the issue was parsing the column names from the vector into the function? I tried using [[col]] but that didn't work either...
