There is possibly a bug with the matrix
class s.t. attributes cannot be set. One workaround is to 'upcast' it to a sexp
and set the attributes via that interface.
Two other notes about your MWE:
- Initialising an item in a list with
NULL
throws an error; instead use R_NilValue
which is R's 'NULL' expression.
- The MWE copies the original object and modifies the copy (see cpp11's copy-on-write semantics "Copy-on-write semantics" in the cpp11 "Motivations" vignette); this may not be your intention with the function.
If you do not wish to modify the column names of the original object, then the following code is a correct implementation of the MWE:
#include "cpp11.hpp"
using namespace cpp11;
[[cpp11::register]]
sexp cpp_colnames(writable::doubles_matrix<> X) {
sexp X_sexp(X.data());
X_sexp.attr("dimnames") = writable::list(
{ R_NilValue, writable::strings({"A", "B"}) }
);
return X_sexp;
}
// > X <- matrix(as.numeric(1:4), nrow=2)
// > cpp_colnames(X)
// A B
// [1,] 1 3
// [2,] 2 4
// > X
// [,1] [,2]
// [1,] 1 3
// [2,] 2 4
Otherwise, if you do want to modify the original object (see "How do I modify a vector in place?" in the cpp11 FAQ) then:
#include "cpp11.hpp"
using namespace cpp11;
[[cpp11::register]]
void cpp_colnames(sexp X_sexp) {
X_sexp.attr("dimnames") = writable::list(
{ R_NilValue, writable::strings({"A", "B"}) }
);
}
// > X <- matrix(as.numeric(1:4), nrow=2))
// > cpp_colnames(X)
// > X
// A B
// [1,] 1 3
// [2,] 2 4