Writing Efficient R Code
Colin Gillespie
Jumping Rivers & Newcastle University
# 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)
# Original
total <- apply(df, 1, sum)
# Updated
total <- rowSums(df)
# Original
is_double[1] & is_double[2] & is_double[3]
# Updated
is_double[1] && is_double[2] && is_double[3]
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