Get startedGet started for free

Sum of double vector

Since loops typically run much faster in C++ than in R, writing loops is an important skill. Let's start with a function that sums values from a NumericVector. This revisits the skills you learned in Chapter 2 Exercise 10, and the previous exercise in this chapter.

This exercise is part of the course

Optimizing R Code with Rcpp

View Course

Exercise instructions

  • Complete the definition of a function, sum_cpp, that loops over elements of a NumericVector and return its sum.
    • Set n to be the size() of x.
    • Initialize result to zero.
    • Specify the for loop arguments. Initialize i to 0, set the iteration condition as i less than n, and increment i by one on each step.
    • In each iteration, add the ith element of x to result.

Hands-on interactive exercise

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

#include 
using namespace Rcpp;

// [[Rcpp::export]]
double sum_cpp(NumericVector x) {
  // The size of x
  int n = ___;
  // Initialize the result
  double result = ___;
  // Complete the loop specification
  for(int i = 0; ___; ___) {
    // Add the next value
    result = result + ___;
  }
  return result;
}

/*** R
set.seed(42)
x <- rnorm(1e6)
sum_cpp(x)
# Does the function give the same answer as R's sum() function?
all.equal(sum_cpp(x), sum(x))
*/
Edit and Run Code