1. Learn
  2. /
  3. Courses
  4. /
  5. Writing Efficient R Code

Exercise

Use && instead of &

To determine if both dice are the same, the move_square() function uses if statements.

if (is_double[1] & is_double[2] & is_double[3]) {
    current <- 11 # Go To Jail - square 11 == Jail
}

The & operator will always evaluate both its arguments. That is, if you type x & y, R will always try to work out what x and y are. There are some cases where this is inefficient. For example, if x is FALSE, then x & y will always be FALSE, regardless of the value of y. Thus, you can save a little processing time by not calculating it. The && operator takes advantage of this trick, and doesn't bother to calculate y if it doesn't make a difference to the overall result.

In this code, if is_double[1] is FALSE we don't need to evaluate is_double[2] or is_double[3], so we can get a speedup by swapping & for &&.

One thing to note is that && only works on single logical values, i.e., logical vectors of length 1 (like you would pass into an if condition), but & also works on vectors of length greater than 1.

Instructions

100 XP
  1. Create an improved_move() function, which is similar to move(), but uses &&.
  2. Using microbenchmark(), compare improved_move() to the previous version move().