Page 55 - Applied Statistics with R
P. 55

3.3. PROGRAMMING BASICS                                            55



                                                     1    
                                                  2
                                                 ̂    =  ∑(   − ̄  ) 2
                                                       
                                                         =1
                      get_var = function(x, biased = FALSE) {
                        n = length(x) - 1 * !biased
                        (1 / n) * sum((x - mean(x)) ^ 2)
                      }


                      get_var(test_sample)


                      ## [1] 14.56753

                      get_var(test_sample, biased = FALSE)


                      ## [1] 14.56753

                      var(test_sample)


                      ## [1] 14.56753


                      We see the function is working as expected, and when returning the unbiased
                      estimate it matches R’s built in function var(). Finally, let’s examine the biased
                                  2
                      estimate of    .
                      get_var(test_sample, biased = TRUE)


                      ## [1] 13.11077
   50   51   52   53   54   55   56   57   58   59   60