If you are open to C ++ instead of C, then Rcpp can make this a little easier. We simply create a list object with row and column names, as in R, and assign this to the dimnames attribute of the dimnames object:
R> library(inline) # to compile, link, load the code here R> src <- ' + Rcpp::NumericMatrix x(2,2); + x.fill(42); // or more interesting values + // C++0x can assign a set of values to a vector, but we use older standard + Rcpp::CharacterVector rows(2); rows[0] = "aa"; rows[1] = "bb"; + Rcpp::CharacterVector cols(2); cols[0] = "AA"; cols[1] = "BB"; + // now create an object "dimnms" as a list with rows and cols + Rcpp::List dimnms = Rcpp::List::create(rows, cols); + // and assign it + x.attr("dimnames") = dimnms; + return(x); + ' R> fun <- cxxfunction(signature(), body=src, plugin="Rcpp") R> fun() AA BB aa 42 42 bb 42 42 R>
The actual assignment of column and row names is so manual ... because the current C ++ standard does not allow direct assignment of vectors during initialization, but that will change.
Edit: I just realized that I can of course use the static create() method for the row and column name, which makes this a little easier and shorter.
R> src <- ' + Rcpp::NumericMatrix x(2,2); + x.fill(42); // or more interesting values + Rcpp::List dimnms = // two vec. with static names + Rcpp::List::create(Rcpp::CharacterVector::create("cc", "dd"), + Rcpp::CharacterVector::create("ee", "ff")); + // and assign it + x.attr("dimnames") = dimnms; + return(x); + ' R> fun <- cxxfunction(signature(), body=src, plugin="Rcpp") R> fun() ee ff cc 42 42 dd 42 42 R>
Thus, we reduce to three or four operators, without monkeys with PROTECT / UNPROTECT and without memory management.
source share