Get startedGet started for free

Change the data frame to a matrix

One of the parts of the code that profvis highlighted was the line where we generated the possible dice rolls and stored the results in a data frame:

df <- data.frame(d1 = sample(1:6, 3, replace = TRUE),
                d2 = sample(1:6, 3, replace = TRUE))

We can optimize this code by making two improvements:

  • Switching from a data frame to a matrix
  • Generating the 6 dice rolls in a single step

This gives

m <- matrix(sample(1:6, 6, replace = TRUE), ncol = 2)

This exercise is part of the course

Writing Efficient R Code

View Course

Exercise instructions

  • Read and understand the data frame solution d().
  • Complete the matrix solution, m().
    • m() should create a matrix with 6 elements and 2 columns.
  • Use the microbenchmark() function to compare the timings of d() and m().

Hands-on interactive exercise

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

# Load the microbenchmark package
___

# The previous data frame solution is defined
# d() Simulates 6 dices rolls
d <- function() {
  data.frame(
    d1 = sample(1:6, 3, replace = TRUE),
    d2 = sample(1:6, 3, replace = TRUE)
  )
}

# Complete the matrix solution
m <- function() {
  ___(sample(1:6, ___, replace = TRUE), ___)
}

# Use microbenchmark to time m() and d()
___(
 data.frame_solution = d(),
 matrix_solution     = ___
)
Edit and Run Code