Get startedGet started for free

Calculating row sums

The second bottleneck identified was calculating the row sums.

total <- apply(d, 1, sum)

In the previous exercise you switched the underlying object to a matrix. This makes the above apply operation three times faster. But there's one further optimization you can use - switch apply() with rowSums().

This exercise is part of the course

Writing Efficient R Code

View Course

Exercise instructions

  • Complete the r_sum() function using rowSums().
  • Use the microbenchmark() function to compare the timings of app() and r_sum().

Hands-on interactive exercise

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

# Example data
rolls

# Define the previous solution 
app <- function(x) {
    apply(x, 1, sum)
}

# Define the new solution
r_sum <- function(x) {
    ___(x)
}

# Compare the methods
microbenchmark(
    app_sol = app(rolls),
    r_sum_sol = ___
)
Edit and Run Code