'Setting colnames in R's cpp11

Provided that cpp11 does not provide any "sugar", we need to use attributes.

I am trying to set colnames in a C++ function, as in the next MWE

#include "cpp11.hpp"
using namespace cpp11;

// THIS WORKS
[[cpp11::register]]
doubles cpp_names(writable::doubles X) {
    X.attr("names") = {"a","b"};
    return X;
}

// THIS WON'T
[[cpp11::register]]
doubles_matrix<> cpp_colnames(writable::doubles_matrix<> X) {
    X.attr("dimnames") = list(NULL, {"A","B"});
    return X;
}

How can I pass a list with two vectors, one NULL and the other ("a","b"), that can be correctly converted to a SEXP?

In Rcpp, one would do colnames(X) = {"a","b"}.

My approach can be wrong.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source