class: center, middle, inverse, title-slide # Day Thirty-Four: Functions ## SDS 192: Introduction to Data Science ###
Lindsay Poirier
Statistical & Data Sciences
, Smith College
###
Spring 2022
--- # Why write functions? * Sometimes we find ourselves writing very similar lines of code over and over again for different data frames or variables. * Example: ```r df1 %>% summmarize(Total = sum(num_votes)) df2 %>% summmarize(Total = sum(num_votes)) df3 %>% summmarize(Total = sum(num_votes)) ``` --- # Functions * Statements organized to perform a specific task * Take arguments as *inputs* * Arguments can be required or optional * Return a value or set of values as *outputs* * Default value is output of last line of function if not specified --- # User-defined Functions Basic format: ```r function_name <- function(arg1, arg2) { x <- #Some code goes here referencing arg1 and arg2 return(x) } ``` --- # Calling Functions > This is the same way you'd call functions built-in to `R` ```r function_name(value_for_arg1, value_for_arg2) ``` --- # User-defined Functions ```r sum_x_in_df <- function(data) { summed_df <- data %>% summarize(Total = sum(var)) return(summed_df) } ``` ```r sum_x_in_df(df1, num_votes) ``` > `data` is a required argument above. --- # Making arguments optional ```r sum_x_in_df <- function(data, var = num_votes) { summed_df <- data %>% summarize(Total = sum({{var}})) return(summed_df) } ``` ```r sum_x_in_df(df1) ``` > Default value provided for `var`. > Use `{{...}}` to pass a variable name in a function. --- # Overriding Defaults ```r sum_x_in_df <- function(data, var = num_votes) { summed_df <- data %>% summarize(Total = sum({{var}})) return(summed_df) } ``` ```r sum_x_in_df(df1, num_registrations) ``` > `num_registrations` overrides the default value of `num_votes` for argument `var` --- # Naming Arguments ```r sum_x_in_df <- function(data, var = num_votes) { summed_df <- data %>% summarize(Total = sum({{var}})) return(summed_df) } ``` ```r sum_x_in_df(data = df1, var = num_registrations) ``` > Order matters if arguments not named!