Exercise

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)

Instructions

100 XP
  • 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().