3 min read

The 12 R functions of Xmas pt2/6

R at Xmas

R at Xmas

Yesterday I posted the first two of the 12 small and hopefully fun R functions that I challenged myself to write last weekend. If you read that post, you’ll already get the idea. They’re small and fun functions that also do something small and fun!

I wanted to stick to no more than a single function (though I may have cheated a bit in at least one of them) in order to ensure that the scope stayed small and I didn’t distract myself with too many unnecessary features. I also wanted stuff that I could use to help teach my kids more about programming, so a lack of complexity is a benefit there too.

Today’s two functions are both really short. The first has a little URL manipulation and the second is just a straight wrapper around sample().

Roll dice

Christmas is a great time for hanging out with your family and friends and playing a few board games, but so often lost dice will ruin the fun. Well, no more!

roll_dice <- function(num_dice = 1){
  for (roll in 1:num_dice){
    cat(sample(1:6, 1), " ")
  }
}

This function is among the smallest in the collection and just outputs a random number from 1 to 6. The optional num_dice parameter lets you control the number of dice that you roll, in case you need to roll more than one.

> roll_dice(5)
2  3  3  1  5 

The interesting thing about this one is the number of ways it could be adapted or extended. It could even form the basis of a complete game like Sellors-family-favourite, Yacht.

Some ideas for variations and improvements:

  • Write your own coin flip function
  • Support different types of dice, with different number of sides or with different things on the faces
  • Build your own “Story Cubes” game - great to play with younger kids
  • Add a mechanism for re-rolling some of the dice
  • use as the basis for a larger game
  • Build it into a shiny app

That’s it for today. Tomorrow we’re playing “guess what number I’m thinking of” and pretending to be in Sci-Fi movies, so check back then. And as ever, if you do play around with any of this stuff, let me know on Twitter.