6.1 How to make a simple function in R

Let’s imagine the structure of a function:

The black dot on the left is the environment. The two blocks to the right are the function arguments.

Figure 6.1: The black dot on the left is the environment. The two blocks to the right are the function arguments.

Function components

Functions have three parts, formals(), body(), and environment().

Example

coffee_ratings%>%slice(1:3)%>%select(1:5)
#> # A tibble: 3 × 5
#>   total_cup_points species owner                    country_of_origin farm_name 
#>              <dbl> <chr>   <chr>                    <chr>             <chr>     
#> 1             90.6 Arabica metad plc                Ethiopia          "metad pl…
#> 2             89.9 Arabica metad plc                Ethiopia          "metad pl…
#> 3             89.8 Arabica grounds for health admin Guatemala         "san marc…
avg_points <- function(species){
  # this function is for calculating the mean
  avg <-  coffee_ratings %>% 
  filter(species == species) %>% 
  summarise(mean = mean(total_cup_points))
  
  return(avg)
}
avg_points("Arabica")
#> # A tibble: 1 × 1
#>    mean
#>   <dbl>
#> 1  82.1
formals(avg_points)
#> $species
body(avg_points)
#> {
#>     avg <- coffee_ratings %>% filter(species == species) %>% 
#>         summarise(mean = mean(total_cup_points))
#>     return(avg)
#> }
environment(avg_points)
#> <environment: R_GlobalEnv>

Functions uses attributes, one attribute used by base R is srcref, short for source reference. It points to the source code used to create the function. It contains code comments and other formatting.

attr(avg_points, "srcref")
#> NULL