Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting *only* column names in Rcpp

Tags:

r

rcpp

I want to set a matrix's column names only using Rcpp, but leave the row names unchanged. So far as I can tell, the dimnames attribute only sets both. For example:

  • R extension in C, setting matrix row/column names
  • http://dirk.eddelbuettel.com/code/rcpp/Rcpp-FAQ.pdf (p.13)

Here's a minimal example of what I want to do, but just in Rcpp instead of R:

my.mat <- diag(3)
colnames( my.mat ) <- c( "A", "B", "C")
my.mat
     A B C
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1

Is there a way to do this?

like image 684
squipbar Avatar asked Feb 14 '15 22:02

squipbar


1 Answers

Newer versions of Rcpp provides rownames() and colnames() which function as their R counterparts do:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericMatrix test(NumericMatrix x)
{
    rownames(x) = CharacterVector::create("a", "b", "c");
    colnames(x) = CharacterVector::create("A", "B", "C");
    return x;
}

/*** R
test(matrix(1:9, nrow = 3))
*/

gives me

> test(matrix(1:9, nrow = 3))
  A B C
a 1 4 7
b 2 5 8
c 3 6 9
like image 122
Kevin Ushey Avatar answered Oct 02 '22 06:10

Kevin Ushey