2.6 Functions
Open the slides in a new tab here.
Exercises
- Create a function that takes a vector of numbers and returns the standard deviation manually (like we did the mean). Use
ifstatements to check if the vector has only one (or fewer) elements and returnNAif so. (Hint: thelength()function will be helpful!) You don’t need any extra arguments besides the vector of numbers.
Modify your function to remove the NA values before calculating the standard deviation. (Hint: the
na.omit()function will be helpful!) Add an argumentna.rm =that defaults toTRUE(the opposite of thena.rmargument in the built-in R functionsd()). Ifna.rm = FALSE, then the function should returnNAif there are any NA values in the vector.What is the standard deviation of income in (all of) NLSY? Compare with the built-in R function
sd().