diff --git a/lecture-06/adds_numbers.cpp b/lecture-06/adds_numbers.cpp index 048c988..6943f65 100644 --- a/lecture-06/adds_numbers.cpp +++ b/lecture-06/adds_numbers.cpp @@ -15,13 +15,25 @@ NumericVector add_vectors(NumericVector a, NumericVector b) { } // [[Rcpp::export]] -NumericVector add_vectors2(NumericVector a, NumericVector b) { +Rcpp::NumericVector add_vectors2( + Rcpp::NumericVector & a, + const Rcpp::NumericVector & b +) { + + a = a + 1; + + if (a.size() != b.size()) + Rcpp::stop("Adding two vectors of different size!"); + return a + b; } /*** R add_vectors(1:5, 1:5) -add_vectors2(1:5, 1:5) + +a <- 1:5 +add_vectors2(a, 1:5) +a */ diff --git a/lecture-06/person-example.cpp b/lecture-06/person-example.cpp new file mode 100644 index 0000000..e485874 --- /dev/null +++ b/lecture-06/person-example.cpp @@ -0,0 +1,55 @@ +#include + +class Person { +public: + Person(std::string name, int age) : + name(name), age(age) {} + std::string get_name() const { return name; } + int get_age() const { return age; } + void print() const {Rprintf( + "%s is %d years old\n", name.c_str(), age); + } + +private: + std::string name; + int age; +}; + +// [[Rcpp::export]] +Rcpp::XPtr create_person( + std::string name, int age +) { + Rcpp::XPtr person(new Person(name, age)); + + // Adding an attribute + person.attr("class") = "MyPerson"; + + return person; +} + +// [[Rcpp::export]] +std::string get_name(SEXP person) { + Rcpp::XPtr p(person); + return p->get_name(); +} + +// [[Rcpp::export]] +int print_person(SEXP person) { + Rcpp::XPtr p(person); + p->print(); + return 0; +} + +/*** R + +# This is an S3 method for printing MyPerson +print.MyPerson <- function(x) { + print_person(x) +} + +george <- create_person("george", 123) + +# These two are equivalent +george +print(george) +*/