Intro to Data Science

Lecture 8 – Custom Functions

A Guide to Your Process

Scheduling

Learning Objectives

Practice

Supporting Information

Class Discussion

Today’s Plan

  • Muddiest Point Review
  • Custom Functions
  • Free Work

Today’s Learning Objectives

After today’s session you will be able to:

  • Describe the process of writing a new function
  • Create a custom function to perform arithmetic

Muddiest Point Review

  • Recurring topics from most recent MPs:


  • What other topic(s) would you like to review?

What is a “Custom Function”?

  • We’ve been working with functions throughout the course
    • These functions have come from packages we can install from CRAN


  • However, R also lets you write your own functions!


  • Functions you write are called custom functions

Why Write Functions?

  • Rewriting / duplicating anything is risky
    • Chance for human error when you’re typing
    • Typos make each “copy” potentially give different results


  • Instead you could write/use a custom function!


  • Functions are a “single source of truth”
    • Something went wrong? Fix the function!


  • Can also share function scripts with friends to make their lives easier

Special Syntax Note

  • R Uses the following special syntax for creating functions
    • You have to use the function function


  • Example syntax:
# Define function name
multiply <- function(arg1, arg2){
  
  # Multiply the arguments together
  result <- arg1 * arg2
  
  # Return that to the user
  return(result)
  
} # End function operations

# Once created, it can be used!
multiply(arg1 = 10, arg2 = 5)
[1] 50
  • Looks kind of like a conditional or loop, right?

Process of Function Writing

  • My tips for success in custom function writing:
  1. Write a normal script that does what you want your function to do


  1. Identify which part(s) of the script you want the function user to specify
    • These will be the arguments!


  1. Do the special formatting to make R recognize it as a function


  1. Use the function like you would any other!

Custom Function Demo

  • Let’s create a function together for practice!


  • Following my tips:
    1. Write the script version of the function
    2. Figure out what the function user should have control over
    3. Make R consider it a function
    4. Use our new function!

Demo Step 1: Write Script

  • Let’s make a function that adds two numbers together
    • Artificially simple, I know, but useful to learn with!


  • We begin by making the script version of our function
# Add two numbers together
4 + 3
[1] 7

Demo Step 2: Identify Inputs

  • Now we identify what the user of our function should be able to control


  • If the function adds two numbers together, the user:
    • Should control the first number
    • Should control the second number
    • Should not control the plus sign


  • Let’s replace our numbers with objects
# Make objects
x <- 4
y <- 3

# Add two objects together
x + y
[1] 7

Demo Step 3: Special Format

  • We can now make this a real function!


  • Define the function using special R syntax
# Define function
plus <- function(x, y){
  
  # Add arguments together
  result <- x + y
  
  # Return that
  return(result)
}

Demo Step 4: Use Function!

  • Now that the function exists, we can use it just like any other function


  • Add 4 and 3 together using our new function
# Define function
plus(x = 4, y = 3)
[1] 7

Write Your Own!

  • Write a function that converts pounds (lb) to kilograms (kg)
    • Formula: (pound / 2.2) = kilograms


  • Remember my tips:
    1. Write it like a normal script
    2. Replace values a user would change with objects
    3. Use special R syntax
    4. Then use the function!


  • Let me know when you’ve finished your function
    • Or if you need help!

Temperature Check

How are you Feeling?

Comic-style graph depicting someone's emotional state as they debug code (from initial struggle and defeat to eventual triumph)

Argument Defaults

  • You can set argument defaults when you create a function


  • Advantage: user doesn’t have to specify all arguments


  • How do we do this?
    • Set it in the function parentheses!

Default Example

  • Let’s define defaults in our addition function
# Define function
plus <- function(x = 4, y = 3){
  
  # Add arguments together
  result <- x + y
  
  # Return that
  return(result) }


  • We can then use the function without specifying those arguments
plus()
[1] 7


  • If the user specifies an argument differently, their input “wins”
plus(x = 10)
[1] 13

Make a Default

  • Let’s revisit your pound to kilogram function


  • Set the default pounds to 175


  • What happens if you run your function with nothing in the parentheses?

Temperature Check

How are you Feeling?

Comic-style graph depicting someone's emotional state as they debug code (from initial struggle and defeat to eventual triumph)

My Goal for You

From Lecture 1!

Comic-style graph depicting someone's confidence with R changing over time

Your Accomplishments

  • In this class, you have done the following:
    • Made and manipulated data
    • Created R scripts and RMarkdown reports
    • Explored version control & GitHub
    • Performed statistical tests
    • Written loops and your own custom function(s)
    • And so much more!


  • If you have a CV/resume, definitely add:
    • Some (or all!) of these skills
    • Link to your GitHub profile

Closing Thoughts

  • I had a lot of fun this summer with y’all!


  • Your development as data scientists has been amazing to witness


  • I particularly loved how you all engaged with the Function Tutorials
    • You really made it your own
    • Found the intersection of your interests and R functions


  • Do you have any last R / data things to discuss?

End of Semester Feedback

  • I really value your feedback!
    • Both on me as an instructor and on the class materials/assignments


  • I may offer this course again and I’d like to improve me/it in the meantime


  • To that end, please fill out the end-of-semester Google Form on Canvas

Upcoming Due Dates

Due before 7/22

(By midnight)

  • Final deadline for all work from a summer course
    • Homework #8
    • GitHub Presence evaluation
    • Optional 3rd draft of Function Tutorials

Free Work

  • Everything is due at the end of course (soon!)


Tips for success:

  1. Check out rubrics and make sure you don’t miss any “easy” points
  2. Don’t leave after this slide!
  3. If you have questions, ask them now during this free work time