CommencerCommencer gratuitement

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().

Cet exercice fait partie du cours

Writing Efficient R Code

Afficher le cours

Instructions

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

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de 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 = ___
)
Modifier et exécuter le code