Skip to content

Latest commit

 

History

History
51 lines (38 loc) · 1019 Bytes

2012-12-10-setting-object-attributes.md

File metadata and controls

51 lines (38 loc) · 1019 Bytes
title author license tags summary layout src
Setting Object Attributes
Hadley Wickham
GPL (>= 2)
basics
Demonstrates setting names and other attributes of R objects from within C++
post
2012-12-10-setting-object-attributes.cpp

All R objects have attributes, which can be queried and modified with the attr method. Rcpp also provides a names() method for the commonly used attribute: attr("names"). The following code snippet illustrates these methods:

{% highlight cpp %} #include <Rcpp.h> using namespace Rcpp;

// [[Rcpp::export]] NumericVector attribs() { NumericVector out = NumericVector::create(1, 2, 3);

out.names() = CharacterVector::create("a", "b", "c"); out.attr("my-attr") = "my-value"; out.attr("class") = "my-class";

return out; } {% endhighlight %}

Here's what the object we created in C++ looks like in R:

{% highlight r %} attribs() {% endhighlight %}

a b c 
1 2 3 
attr(,"my-attr")
[1] "my-value"
attr(,"class")
[1] "my-class"