2.6 Functions

Open the slides in a new tab here.

Exercises

  1. Create a function that takes a vector of numbers and returns the standard deviation manually (like we did the mean). Use if statements to check if the vector has only one (or fewer) elements and return NA if so. (Hint: the length() function will be helpful!) You don’t need any extra arguments besides the vector of numbers.

sd(x)=i=1n(xix¯)2n1

  1. Modify your function to remove the NA values before calculating the standard deviation. (Hint: the na.omit() function will be helpful!) Add an argument na.rm = that defaults to TRUE (the opposite of the na.rm argument in the built-in R function sd()). If na.rm = FALSE, then the function should return NA if there are any NA values in the vector.

  2. What is the standard deviation of income in (all of) NLSY? Compare with the built-in R function sd().

Resources