6.1 How to make a simple function in R
Let’s imagine the structure of a function:

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)
}
body(avg_points)
#> {
#> avg <- coffee_ratings %>% filter(species == species) %>%
#> summarise(mean = mean(total_cup_points))
#> return(avg)
#> }
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.