Skip to main content
Statistics LibreTexts

15.1: Generating Random Samples (Section @ref{generating-random-numbers})

  • Page ID
    8799
  • Here we will generate random samples from a number of different distributions and plot their histograms.

    nsamples <- 10000
    nhistbins <- 100
    
    # uniform distribution
    
    p1 <-
      tibble(
        x = runif(nsamples)
      ) %>% 
      ggplot((aes(x))) +
      geom_histogram(bins = nhistbins) + 
      labs(title = "Uniform")
    
    # normal distribution
    p2 <-
      tibble(
        x = rnorm(nsamples)
      ) %>% 
      ggplot(aes(x)) +
      geom_histogram(bins = nhistbins) +
      labs(title = "Normal")
    
    # Chi-squared distribution
    p3 <-
      tibble(
        x = rnorm(nsamples)
      ) %>% 
      ggplot(aes(x)) +
      geom_histogram(bins = nhistbins) +
      labs(title = "Normal")
    
    # Chi-squared distribution
    p3 <-
      tibble(
        x = rchisq(nsamples, df=1)
      ) %>% 
      ggplot(aes(x)) +
      geom_histogram(bins = nhistbins) +
      labs(title = "Chi-squared")
    
    # Poisson distribution
    p4 <-
      tibble(
        x = rbinom(nsamples, 20, 0.25)
      ) %>% 
      ggplot(aes(x)) +
      geom_histogram(bins = nhistbins) +
      labs(title = "Binomial (p=0.25, 20 trials)")
    
    
    plot_grid(p1, p2, p3, p4, ncol = 2)

    file76.png