Making Functions practice

Schwab

Functions

  • Inputs and outputs

  • Can set defaults arguements

  • Can be general or specific to a package.

    • n() vs. read_all_contributions()
  • Save time in the long run.

Function outline

Greeting <- function(arg1 = "Hello" ){
  print(arg1)
}
Greeting()
[1] "Hello"
Greeting("Hiya")
[1] "Hiya"

This function will add

adding <- function(x,y){
  
  total <- sum( c( x , y ))
  
  return(total)
}

adding(2,4)
[1] 6
#adding()

This function will multiply

multiplying <- function(x = 1, y = 1){
  total <- x*y
  total
}

multiplying()
[1] 1
multiplying(2,4)
[1] 8

if, else if, else

The computer can run a logical check.

Consider this function:

umbrella <- function(weather = "sunny"){

if(weather == "no precipitation"){
  
    print("leave umbrella at home")
    }
    
else if(weather == "snow"){

    print("You don't need an umbrella")
}
  
else{
    print("bring an umbrella")
    
    }
}
umbrella(weather = "snow")
[1] "You don't need an umbrella"

This is a composite function

Depending in an argument

my_1st_calculator <-function(x,y,operation="add"){
  
  if(operation %in% "add"){
    total <- adding(x,y)
  }
  
  else if(operation %in% "multiply"){
    total <- multiplying(x,y)
  }
  
  else{
    stop("Please choose `add` or `multiply` for the operation argument")
  }
  
  return(total)
}
my_1st_calculator(1,6, operation="multiply")
[1] 6

Try one

Make a function that takes a vector of students in this class and prints the name of each student.

library(tidyverse)
library(googlesheets4)

class_info <- read_sheet("https://docs.google.com/spreadsheets/d/1XOAFQvBcFvhKwEl5xH6l3nRJK2Wk0hWZ18S9kAZclQ0/edit?usp=sharing") |>
  janitor::clean_names()

# selecting only the column we are interested in and making it into a vector.
name_vector <- as.vector( 
  class_info |>
    select("preferred_name"))