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
Exercise instructions
- Complete the definition of a function,
sum_cpp, that loops over elements of aNumericVectorand return its sum.- Set
nto be thesize()ofx. - Initialize
resultto zero. - Specify the
forloop arguments. Initializeito0, set the iteration condition asiless thann, and incrementiby one on each step. - In each iteration, add the ith element of
xtoresult.
- Set
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))
*/