Will Will - 23 days ago 10
R Question

Graphing with Loops in R

I'm trying to use a loop to graph histograms based on a condition (class(variable)='numeric'), but I'm not getting any output and I'm not sure why.

Code:

for (i in length(df)){
if (class(df[,i])=="numeric"){
hist(df[,i])
}
}


hist(df[,15]) returns a histogram, and class(df[,15]) = 'numeric', so I'm not sure where the error is coming from.

Answer Source

I think you may just have a small typo - it should be for (i in 1:length(df)) rather then just length(df) (the latter will only produce a single plot for the last column). Here is a quick example:

df <- ChickWeight
for (i in 1:length(df)){
  if (is.numeric(df[, i])) {
   hist(df[, i])
  }
}

Edit: Just saw that @Richard Lusch already commented this while I was typing out the answer (I hate when that happens!) If you want to post yours as an answer, I can delete mine!