library(tidyverse)
library(ggplot2)
::opts_chunk$set(echo = TRUE, warning=FALSE, message=FALSE) knitr
Challenge 9
challenge_9
Creating a function
Challenge Overview
Today’s challenge is simple. Create a function, and use it to perform a data analysis / cleaning / visualization task:
Examples of such functions are: 1) A function that reads in and cleans a dataset.
2) A function that computes summary statistics (e.g., computes the z score for a variable).
3) A function that plots a histogram.
That’s it!
<- function(x) {
get_summary_statistics <- mean(x)
mean <- median(x)
median <- sd(x)
std_dev <- min(x)
min_val <- max(x)
max_val <- c(mean, median, std_dev, min_val, max_val)
result names(result) <- c("Mean", "Median", "Standard Deviation", "Minimum", "Maximum")
return(result)
}<- c(90, 85, 77, 69, 71, 80, 65, 83, 53, 95, 94, 90, 87, 71, 70, 65, 58, 59, 98, 90, 87, 76)
test_scores get_summary_statistics(test_scores)
Mean Median Standard Deviation Minimum
77.86364 78.50000 13.07231 53.00000
Maximum
98.00000
<- x >= 50 condition
Error in eval(expr, envir, enclos): object 'x' not found
<- function(test_scores, condition) {
exclude_outliers <- keep(test_scores, condition)
no_outliers_test_scores return(no_outliers_test_scores)
}
At the top of the file, we define our function “get_summary_statistics”. Then we code how we want it to interpret the input, and what that input is supposed to be, in this case a group of test scores. Our function computes the mean, median, standard dev., min, and max of our test scores, and returns the results to the console for viewing. Voila!