Exercise

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.

Instructions

100 XP
  • 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.