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 aNumericVector
and return its sum.- Set
n
to be thesize()
ofx
. - Initialize
result
to zero. - Specify the
for
loop arguments. Initializei
to0
, set the iteration condition asi
less thann
, and incrementi
by one on each step. - In each iteration, add the ith element of
x
toresult
.
- 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))
*/