Search code examples
rhistogramgraphing

How to add titles from a list to a series of histograms?


Is it possibile to attach titles via an apply-family function to a series of histograms where the titles are picked from a list?

The code below creates three histograms. I want to give each a different name from a list (named "list"), in order. How do I do this?

data <- read.csv("outcome-of-care-measures.csv")
outcome <-data[,c(11,17,23)]
out <- apply(outcome, 2,as.data.frame) 
par(mfrow=c(3,1))
apply(outcome,2, hist, xlim=range(out,na.rm=TRUE), xlab="30 day death rate") 

Solution

  • As it is not only the columns but another argument that changes, you may use mapply to have a function from the apply family.

    args <- list(xlim=range(data, na.rm=TRUE), xlab="30 day death rate")
    titles <- list("Title 1", "Title 2", "Title 3")
    par(mfrow=c(3,1))
    mapply(hist, data, main=titles, MoreArgs=args)
    

    If you wrap the invisible function around the last line you can avoid the console output.

    enter image description here

    Note: I think using loops here is far more straightforward.