Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
gvegayon committed Sep 24, 2024
1 parent 85731f1 commit a3910b3
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 2 deletions.
16 changes: 14 additions & 2 deletions lecture-06/adds_numbers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/


55 changes: 55 additions & 0 deletions lecture-06/person-example.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#include <Rcpp.h>

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<Person> create_person(
std::string name, int age
) {
Rcpp::XPtr<Person> person(new Person(name, age));

// Adding an attribute
person.attr("class") = "MyPerson";

return person;
}

// [[Rcpp::export]]
std::string get_name(SEXP person) {
Rcpp::XPtr<Person> p(person);
return p->get_name();
}

// [[Rcpp::export]]
int print_person(SEXP person) {
Rcpp::XPtr<Person> 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)
*/

0 comments on commit a3910b3

Please sign in to comment.