Homework 1

Write a function to calculate the standard deviation

Standard deviation (sigma), is a measure of the variation from the mean. A high SD means there is more variation in the data around the mean.

The standard deviation is calculated by:

  1. Taking the difference of each data point from the mean
  2. Squaring the result of each difference from the mean
  3. Taking the average of those values
  4. Squaring the result.

METHOD 1: We can do this by using R as a calculator:

myData <- c(16, 18, 14, 22, 27, 17, 19, 17, 17, 22, 20, 22)
myData_deviations <- myData - mean(myData)
myData_deviationsSquared <- myData_deviations^2
myData_deviationsSquaredMean <- mean(myData_deviationsSquared)
sqrt(myData_deviationsSquaredMean)
## [1] 3.394

METHOD 2: Or, we can write a function to complete the operations, and then use that function for any set of data that we might have:

mySDfunction <- function(someData) {
    dev <- (someData - mean(someData))^2
    SD <- sqrt(mean(dev))
    return(SD)
}

Next, run the function on your data set:

mySDfunction(myData)
## [1] 3.394