background picture with networks
Module 1 | Lesson 8

Create functions. Ditch duplication.

The use of functions is a cornerstone of clean and effective programming. If you find yourself with a lot of duplication in your code, you need this.

Members only
12 minutes read

Duplication duplication duplication...

Have you ever seen an R script that looks like this:

print(
  round(mean(subset(
    na.omit(data), species == "Adelie" & island == "Torgersen"
  )$bill_length_mm), 2)
)
print(
  round(mean(subset(
    na.omit(data), species == "Adelie" & island == "Biscoe"
  )$bill_length_mm), 2)
)
print(
  round(mean(subset(
    na.omit(data), species == "Adelie" & island == "Dream"
  )$bill_length_mm), 2)
)

The same thing is done 3 times: once for Torgersen, once for Biscoe and once for Dream.

This code is very hard to work with:

Hard to read: that's a lot of code!

Hard to maintain: if you want to change something, you will have to make the change 3 times.

Error prone: one day, you will update all items and insert a bug in one. Or you will update an item and forget about the others.


It's time to create a function!

background picture with networks
Productive R Workflow

This lesson is for members only! 😔
Become a member now to access the full course with a lifetime access!

Or Login

← Previous

Read from Excel directly

Next →

Split your work