简体   繁体   中英

Setting *only* column names in 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:

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM