Chapter 12 A note on reading other people’s code

You may want follow this workshop because you want to understand what your collaborators or students are doing, and they happen to use R. Great!

Here is the bad news: There are many ways to the top of the mountain, and also in R there are many ways to achieve the same result. Say you want an average of a variable in your dataset, then below are some ways in which to do that:

df <- data.frame(scores = c(1, 2, 3, 4, 5, 6))
mean(df[,1])
mean(df[[1]])
mean(df[, "scores"])
mean(df$scores)
with(df, mean(scores))
df %>% pull(scores) %>% mean
df %>% summarise(mean = mean(scores))

Of course there are even more ways to do things when the programmers creates her own functions and workflows. This means that it isn’t particularly easy to read other’s code. This also holds for future you, who will be the most likely person reading and reviewing the code.

Here is why the bad news is not that bad:

  • maybe we can agree that it is very important to annotate code properly, for collaborators and future you. You can do that by commenting your code in R-scripts (with the “#”). Even better would be to do some form of literate programming, where you combine text with code. Not unlike this website! Rmarkdown or Quarto are great ways to do this.

  • at least knowing some R-code already means that an R-script you receive is not daunting any more.

  • a large part of collaborating is not necessarily understanding all code, but certainly being able to reproduce the output of the code.