Simple C++ Expressions with evalCpp
Unlike R, you don't have access to a console in C++ to experiment iterations of your code.
To ease into C++ gradually, Rcpp
provides the evalCpp()
function
that takes a simple C++ expression as a string,
compiles it into a proper C++ function, and calls that function.
This is often used to check if a machine is properly configured to
work with Rcpp
.
This exercise is part of the course
Optimizing R Code with Rcpp
Exercise instructions
- Load the
Rcpp
package. - Evaluate
2 + 2
as a C++ expression withevalCpp()
and also as an R expression. - What are the storage modes of
x
andy
? - Change the C++ expression
2 + 2
so that it returns a double and assign it toz
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Load Rcpp
___
# Evaluate 2 + 2 in C++
x <- evalCpp(___)
# Evaluate 2 + 2 in R
y <- ___
# Storage modes of x and y
___
___
# Change the C++ expression so that it returns a double
z <- evalCpp("2 + 2")