Search code examples
rlistfor-loophistogramgamma-distribution

how do I plot this histogram in R


So looking at this question here

"Let A = {0.1, 0.5, 1, 2, 5, 10, 100} L = {0.1, 0.5, 1, 2, 5, 10, 100}

  1. For each pair (α, λ) ∈ A × L above, use the built-in R function rgamma() to generate samples of size 10, 000 each from the Gamma(α, λ) distribution. (Do not include your sample in the output!) This will give you 7 × 7 = 49 random samples of size 10, 000 each. These are your datasets you will base the rest of the assignment on.
  2. Use the function hist() to plot histograms of your sample datasets. I want 49 histogram. If you can arrange them into a nice 7-by-7 grid, all the better. Clearly label your plots. Remember to play around with the breaks options and choose an appropriate number of bins so that your plots have nicely defined shapes."

Im trying for Q2 and would like to know what Im doing wrong here and even is my Q 1 right

#Question 1

set.seed(10000)

v <- c(0.1,0.5,1,2,5,10,100)
u <- c()
for(i in v)
{
  for(j in v)
  {
    u <- c(u,paste0(i,"-",j))
  }
}


#Question 2

lyst <- list()
q <- 1
for (i in v)
{
  m <- matrix(nrow=10000)
  for (j in v)
  {
    m <- cbind(m,rgamma(10000,i,j))
  }
  m <- m[,-1]
  colnames(m) <- paste0(rep(as.character(i),7),"-",as.character(j))
  lyst[[q]] <- m
  q <- q + 1
}
pdf("Hist8.pdf",width = 20,height = 10)
for(x in 1:7)
{
  for(y in 1:7)
  {
    hist(lyst[[x]][,y],
    xlab = "Value",
    main = paste("Alpha-Lambda:",
    colnames(lis[[x]])[y]))
  }
}
dev.off()

I'd appreciate any advice or any sources which can help me with this


Solution

  • Here is a quick modifications from your approach. Instead of trying to store everything in a matrix, I just created a list of the 49 desired distributions and then plotted them 1 by 1.

    #Question 2
    
    lyst <- list()
    #create a list of the 49 distributions
    for (i in v)
    {
      for (j in v)
      {
        elementname<-paste0(as.character(i),"-",as.character(j))
        print(elementname)
        lyst[[elementname]] <- rgamma(10000,i,j)
      }
    }
    
    
    #plot the 49 lists
    #pdf("Hist8.pdf",width = 20,height = 10)
    #define the number of rows and columns (7x7 is probably to many)
    par(mfcol=c(7,7))
    for(x in names(lyst))
    {
        hist(lyst[[x]],
             xlab = "Value",
             main = paste("Alpha-Lambda:", x) )
    
    }
    #dev.off()