Section 8 A tip for understanding R code

When you see a section of R code, it may not be obvious what the code does (although you can sometimes guess from the function names). Consider

x <- rep(2:4, each = 3)
sum(unique(x))
## [1] 9

How did R get the result 9?

It can sometimes help to run sections of the code, to see what each bit does: you can then see the individual steps that get to the result. In particular, you might run sections within a single line.



We first see what the variable x is:

x
## [1] 2 2 2 3 3 3 4 4 4

We can see that the numbers 2, 3, 4 have been repeated (using rep()) three times each. Then we can see what unique(x) does

unique(x)
## [1] 2 3 4

This gets rid of the duplicates in the vector x. So we can see that the last line is working out the sum of 2, 3, 4.