Monopoly recap

Writing Efficient R Code

Colin Gillespie

Jumping Rivers & Newcastle University

Data frames vs. matrices

# Original
rolls <- data.frame(d1 = sample(1:6, 3, replace = TRUE),
                    d2 = sample(1:6, 3, replace = TRUE))
# Updated
rolls <- matrix(sample(1:6, 6, replace = TRUE), ncol = 2)
  • Total Monopoly simulation time: 2 seconds to 0.5 seconds
  • Creating a data frame is slower than a matrix
  • In the Monopoly simulation, we created 10,000 data frames
Writing Efficient R Code

apply vs. rowSums

# Original
total <- apply(df, 1, sum)
# Updated
total <- rowSums(df)
  • 0.5 seconds to 0.16 seconds - 3 fold speed up
Writing Efficient R Code

& vs. &&

# Original
is_double[1] & is_double[2] & is_double[3]
# Updated
is_double[1] && is_double[2] && is_double[3]
  • Limited speed-up
  • 0.16 seconds to 0.15 seconds
Writing Efficient R Code

Overview

Method Time (secs) Speed-up
Original 2.00 1.0
Matrix 0.50 4.0
Matrix + rowSums 0.20 10.0
Matrix + rowSums + && 0.19 10.5
Writing Efficient R Code

Let's practice!

Writing Efficient R Code

Preparing Video For Download...