This is probably a very simple question. But I can not figure out how to fix it.
I have a dataset with lots of columns and I want to run a loop to create histograms for certain columns. I know I can create a list using the column name but is there a way to use indexing instead?
See below an example using iris dataset and error I get.
# Function to repeat histogram over multiple predictor variables
library(datasets)
data(iris)
vars=iris[1:3]
hist <- function(data, var){
p <-
data %>%
ggplot(aes(x = .data[[var]], group=1)) +
geom_histogram(bins = 10) +
theme_classic()
return(p)
}
## prints out the plots as in the loop
lapply(vars, FUN = hist, data = iris)
Error in geom_histogram()
:
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in .data[[<dbl: 5.1, 4.9, 4.7, 4.6, 5, ...>]]
:
! Must subset the data pronoun with a string, not a double vector.
user24531123 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.