Get startedGet started for free

Create vector with given values

Rather than defining a vector, then populating its elements afterwards, it is possible to create a vector and specify its values in a single line of code using ::create(). This is a static member function, that is, it is a method of the vector type itself, rather than a method of a vector variable. You can specify up to 20 elements using create. (For longer vectors, you have to use multiple lines of code.)

The following code creates a numeric vector, important_numbers, containing pi, e, and infinity.

NumericVector numbers = NumericVector::create(PI, exp(1), INFINITY);

::create can also be used to create named vectors. The syntax for naming elements is _["name"] = value. Here is the same code again, this time naming the elements.

NumericVector numbers = NumericVector::create(_["pi"] = PI, _["e"] = exp(1), _["inf"] = INFINITY);

Just as in R, if you want to combine variables of different types into another variable, you use a list. In the Rcpp version, the type is capitalized; it's a List.

This exercise is part of the course

Optimizing R Code with Rcpp

View Course

Exercise instructions

  • Complete the definition of a function, create_vectors(), that creates some vectors.
    • Create an unnamed character vector, polygons, containing the values "triangle", "square", and "pentagon", in that order.
    • Create a named integer vector, mersenne_primes, containing the values 3, 7, and 31, in that order. The names should be "first", "second", and "third".
    • Create a named list, both, containing polygons and mersenne_primes, in that order. The names should also be polygons and mersenne_primes.

Hands-on interactive exercise

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

#include 
using namespace Rcpp;

// [[Rcpp::export]]
List create_vectors() {
  // Create an unnamed character vector
  CharacterVector polygons = CharacterVector::___("___", "___", "___");
  // Create a named integer vector
  IntegerVector mersenne_primes = ___(_["___"] = ___, ___, ___);
  // Create a named list
  List both = ___(___, ___);
  return both;
}

/*** R
create_vectors()
*/
Edit and Run Code