Homework 1: Introduction to R

Dominik Schneider


Assignment

Write a function to compute the standard deviation, use the four steps outlined. Do not use the internal sd() function to check your work because it uses \( \sqrt{\frac{1}{N-1} \sum_{i=1}^N (x_i - \overline{x})^2} \), note the N-1 in the denominator. Your function is correct if you find a standard deviation of around 3.39.

The standard deviation is the Root Mean Square (RMS) of the deviations from the mean. The above formula can be broken down into a series of simple steps:
1. Calculate the deviations from the mean.
2. Square the deviations from the mean, save the squared deviations as a new R object (use the “<-” assignment operator).
3. Take the mean of these squared deviations. Again, save the results as an object.
4. Finally, take the square root of the result from the prior step.

rain <- c(16, 18, 14, 22, 27, 17, 19, 17, 17, 22, 20, 22)
sqdev <- (rain - mean(rain))^2  #Deviations from the mean; squared
sqdev.m <- mean(sqdev)  # mean of the squared deviations;
sqdev.m.sqroot <- sqrt(sqdev.m)  #square root of the mean of squared deviations
sqdev.m.sqroot
## [1] 3.394

Here is a function that does the same thing:

mystd <- function(data) {
    d <- (data - mean(data))^2
    return(sqrt(mean(d)))
}

Evaluate the function to confirm it works:

mystd(rain)
## [1] 3.394