• Introduction To R
  • 1 The Prerequisites
    • 1.1 Why use R and R Studio
      • 1.1.1 More coding, and less point and click
    • 1.2 Wrote by the people for the people
    • 1.3 R has a large community
    • 1.4 R produces high-quality graphics
    • 1.5 Open Source
  • 2 Installing R and R Studio
    • 2.1 Installing R and R studio
    • 2.2 I already have R and RStudio installed.
  • 3 Intro to R Part I
    • 3.1 Getting to know your IDE
  • 4 Operations and Objects
    • 4.0.1 Challenge
  • 5 Packages
    • 5.1 Help files
      • 5.1.1 Help files for package
      • 5.1.2 Help files for funcitons
  • 6 Data Frames
    • 6.1 loading in data frames from a package
    • 6.2 Saving CSV files.
    • 6.3 Creating data frames in R
      • 6.3.1 Challenge
  • 7 Manipulating data frames.
    • 7.1 Slicing a data frame
    • 7.2 Creating new columns
  • 8 Descriptive States in data frames.
    • 8.0.1 Challenge
  • 9 For loops and while loops.
  • 10 If block
    • 10.0.1 Challenge
  • 11 Creating functions.
  • 12 Q and A
  • Published with bookdown

Introduction 2 R

Chapter 11 Creating functions.

Functions are use full when you want to reuse steps to complete a process.

In this example we are going to create a function that returns the amount the batting average based on at-bats and hits.

# Create get-average function
## inside the () you must define the input
get_average <- function(at_bats, hits ){
  
  
  # Create the situation where the player has not had any at-bats. We can not calculate average since we are divding by 0
  if(at_bats==0){
    
    average= NA
  }
  
  ## Create batting average
  if(at_bats>0){
    
    average = hits/at_bats
  }
  
  
  ### use the return() function to define output. 
  return(average)
  
}
get_average(172,41)
## [1] 0.2383721