Sequence of integers
The functions you wrote in previous exercises performed calculations then returned a single number. You can also write functions that return a vector.
The syntax for creating a vector type is to specify the type of the vector followed by the name of the variable, followed by the number of elements in the vector, in parentheses. For example, to create a numeric vector named numbers, containing 10 elements, the code would be as follows.
NumericVector numbers(10);
Deze oefening maakt deel uit van de cursus
Optimizing R Code with Rcpp
Oefeninstructies
- Complete the definition for a function,
seq_cpp(), that takes two integersloandhiand returns anIntegerVectorof the numbers between them.- Set the return type to
IntegerVector. - Create a new integer vector,
sequence, of sizen. - Inside the
forloop, set the ith element ofsequencetoloplusi. - Return
sequence.
- Set the return type to
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
#include
using namespace Rcpp;
// Set the return type to IntegerVector
// [[Rcpp::export]]
___ seq_cpp(int lo, int hi) {
int n = hi - lo + 1;
// Create a new integer vector, sequence, of size n
___;
for(int i = 0; i < n; i++) {
// Set the ith element of sequence to lo plus i
___;
}
return ___;
}
/*** R
lo <- -2
hi <- 5
seq_cpp(lo, hi)
# Does it give the same answer as R's seq() function?
all.equal(seq_cpp(lo, hi), seq(lo, hi))
*/