-1

I want to make histograms for all the quantitative variables in a data frame.

the data can be found here

https://knightsucfedu39751-my.sharepoint.com/:x:/g/personal/peili_knights_ucf_edu/Ea6wk4iPln9DpH-eDQupx60BkN8DaMNdnl7YlKxHfiicdA?e=BIUPca

the code is here:

library(ggplot2)
cereal <- read.csv('Cereals.csv')
quantitative <- c("calories", "protein", "fat", "sodium", "fiber", "carbo", "sugars", "potass", "vitamins", "weight", "cups")
cereal[,quantitative] <- as.numeric(as.character(unlist(cereal[,quantitative])))
    for (variable in quantitative){
                                   plot <- ggplot(cereal, aes(variable)) 
                                           +geom_histogram(binwidth = 0.5)
                                   print(plot)
                                   }

but I always get the error: "StatBin requires a continuous x variable: the x variable is discrete. Perhaps you want stat="count"?"

I have check some solutions such as change geom_histogram to geom_bar or add binwidth = 0.;5 but none of these help.

Does anyone know how to solve this question? Thank you!

Pei Li
  • 302
  • 3
  • 15
  • 1
    Please don't include links to third-party filehosters, as many people around here are loath to download files from obscure sources. Instead use `dput` (or `dput(head(..., n = 20))` to post representative & minimal sample data. For more information (and future posts), see how to provide a [minimal reproducible example/attempt](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Maurits Evers Feb 03 '19 at 03:25

1 Answers1

1

You need to use aes_string instead of aes. Your for loop is passing in a character string i.e. "calories" instead of the object calories.

for (variable in quantitative){
 plot <- ggplot(cereal, aes_string(variable)) +
geom_histogram(binwidth = 0.5)
 print(plot)
 }

now your code is only going to print the last plot because each sequential plot gets erased as the for loop progresses. So you should consider storing the plot objects in a list so you can view them all.

Maxwell Chandler
  • 626
  • 8
  • 18