Page 53 - Applied Statistics with R
P. 53

3.3. PROGRAMMING BASICS                                            53


                         • Give the function a name. Preferably something that is short, but de-
                           scriptive.
                         • Specify the arguments using function()
                         • Write the body of the function within curly braces, {}.


                      standardize = function(x) {
                        m = mean(x)
                        std = sd(x)
                        result = (x - m) / std
                        result
                      }


                      Here the name of the function is standardize, and the function has a single
                      argument x which is used in the body of function. Note that the output of
                      the final line of the body is what is returned by the function. In this case the
                      function returns the vector stored in the variable result.
                      To test our function, we will take a random sample of size n = 10 from a normal
                      distribution with a mean of 2 and a standard deviation of 5.

                      (test_sample = rnorm(n = 10, mean = 2, sd = 5))


                      ##   [1] -0.1456927 -5.5692281   2.9219036  8.6167755   2.8873106 -3.1477341
                      ##   [7]  0.1278323 -0.5568065   1.5051560  1.9603510

                      standardize(x = test_sample)


                      ##   [1] -0.2634915 -1.6844768   0.5402294  2.0323058   0.5311659 -1.0500369
                      ##   [7] -0.1918270 -0.3712048   0.1690366  0.2882993


                      This function could be written much more succinctly, simply performing all the
                      operations on one line and immediately returning the result, without storing
                      any of the intermediate results.

                      standardize = function(x) {
                        (x - mean(x)) / sd(x)
                      }

                      When specifying arguments, you can provide default arguments.


                      power_of_num = function(num, power = 2) {
                        num ^ power
                      }
   48   49   50   51   52   53   54   55   56   57   58