0

I have a problem when creating multiple histograms with a for loop.

So, my initial histogram looks like this:

library(ggplot2)
histosherp <- function(x) {
  ggplot(sherp(x), aes(x=sherpcfu(x))) + geom_histogram(binwidth=0.15) + 
    labs(title=paste("CFU count at", x), x="CFU", y="Number of samples")
}

where sherp and sherpcfu are:

sherp <- function(x) {
  filter(data, PointName == x)
}

sherpcfu <- function(x) {
  sherp(x)$CFUTotal
}

Whenever I call my histosherp() function with a Point Name as an argument it looks great. However, if I try to loop it to get histograms of every point in the PointName list, I get no result.

What I did so far, was exactly this:

univec <- unique(data$PointName, incomparables=FALSE)

histrep <- function(vecx){
  for(i in 1:length(vecx)){
    htrial <- ggplot(sherp(i), aes(x=sherpcfu(i))) + 
      geom_histogram(binwidth=0.15) + 
      labs(title=paste("CFU count at", i), x="CFU", y="Number of samples")}
  htrial
}

histrep(univec)

And there I get a blank histogram (so plot space but no histogram) with the title "CFU count at 10".

What am I doing wrong and how can I get separate histograms (like the one that works for me) but without having to call them by inserting the different Point Names as an argument every time?

Example Data:

The following data is similar to mine but had to simplify as the file is massive.

Column "PointName": ENT08, EXT84, EXT60, ENT35 (repeated around 70 times each).

Column "CFUTotal": Values between 0 and 3, mostly 0 (e.g. 0, 0, 0, 1, 0, 2, 0, etc.)

Row names are namely cardinal numbers.

Marc BF
  • 99
  • 2
  • 10
  • Not sure, but I would try `print(htrial)` in the loop, instead of `htrial`. – Stéphane Laurent Feb 11 '19 at 12:21
  • 1
    Hi, please [provide data](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610), e.g. adding the output of `dput()` or `dput(head())` to your question. You'll have a much better chance of getting a great answer! – jay.sf Feb 11 '19 at 12:28
  • Edited to add data, hope it gets easier now! – Marc BF Feb 11 '19 at 12:40

0 Answers0