Get Started

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.

This is a part of the course

“Writing Efficient R Code”

View Course

Exercise instructions

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

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Example data
is_double

# Define the previous solution
move <- function(is_double) {
    if (is_double[1] & is_double[2] & is_double[3]) {
        current <- 11 # Go To Jail
    }
}

# Define the improved solution
improved_move <- function(is_double) {
    if (is_double[1] ___ is_double[2] ___ is_double[3]) {
        current <- 11 # Go To Jail
    }
}

# microbenchmark both solutions
# Very occassionally the improved solution is actually a little slower
# This is just random chance
microbenchmark(___, ___, times = 1e5)
Edit and Run Code

This exercise is part of the course

Writing Efficient R Code

IntermediateSkill Level
4.2+
26 reviews

Learn to write faster R code, discover benchmarking and profiling, and unlock the secrets of parallel programming.

Profiling helps you locate the bottlenecks in your code. This chapter teaches you how to visualize the bottlenecks using the profvis package.

Exercise 1: What is code profilingExercise 2: Profiling a functionExercise 3: Where's the hold-up?Exercise 4: Profvis in actionExercise 5: Profvis: Larger exampleExercise 6: Change the data frame to a matrixExercise 7: Calculating row sumsExercise 8: Use && instead of &
Exercise 9: Monopoly overview

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free