Over the holiday period my partner was talking about a question she was posed at a work quiz, which was “How many gifts in total are given in the song”The 12 Days of Christmas". I thought this was a great opportunity to showcase some of the basic skills that are useful to master in R, namely functions and *apply.

First, we need to consider how to calculate the number of presents gifted in any given day. Taking day 5 as an example, the gifts given are 5 golden rings, 4 calling birds, 3 french hens, two turtle doves, and the partridge in a pear tree. On day 6 we get gifted all of that again, plus 6 geese a-laying. So for day 5, the number of gifts can be written as:

``1 + 2 + 3 + 4 + 5``

And then day 6 would be:

``1 + 2 + 3 + 4 + 5 + 6``

Therefore, for day n it would be written as

``1 + 2 + 3 ... + n``

This is known as “The Sum of the First N Natural Numbers”, and can be generalised to the formula

``n(n + 1)/2``

Lets implement this formula as a function in R:

``````daily_number_gifts <- function(n) {
n * (n + 1)/2
}``````

Now we can see whether it works.

``daily_number_gifts(4) == (1 + 2 + 3 + 4)``
``##  TRUE``

Great, so our function seems to be working. We can now give it any of the 12 days, and it will tell us how many gifts were given on that day.

Now we need to run this function for each of the values 1 - 12, and sum them up. No need to write the function 12 times though, we can use sapply to pass the vector 1:12 to the function, and it will compute the product for each element of the vector.

Note: Why am I using sapply? So I get a vector returned instead of a list.

``sapply(1:12, daily_number_gifts)``
``##    1  3  6 10 15 21 28 36 45 55 66 78``

We get a vector with the number of gifts for each day. To get the total number, lets just wrap the above in “sum”.

``sum(sapply(1:12, daily_number_gifts))``
``##  364``

And there we go. 364 gifts given over the 12 days of Christmas.