[Rcpp-devel] Getting and setting array dimensions - simpler ways?

Dirk Eddelbuettel edd at debian.org
Mon Sep 10 16:12:26 CEST 2012


On 10 September 2012 at 13:55, Søren Højsgaard wrote:
| Dear list,
| 
| I want to do some operations on an array, here exemplified by taking log (the operations I have in mind are made using RcppArmadillo):
| 
| > pp  <- array(c(.1, .4, .4, .1), dim=c(2,2),dimnames=list(A=c("a1","a2"), B=c("b1","b2")))
| > log(pp)
|     B
| A            b1         b2
|   a1 -2.3025851 -0.9162907
|   a2 -0.9162907 -2.3025851
| 
| It is essential that dim and dimnames attributes are preserved. My take on this task is:
| 
| src <-'
|  using namespace arma;
|  using namespace Rcpp;
|  NumericVector p(pp_);
|  // Some computations using RcppArmadillo
|  vec pp = as<vec>(pp_);
|  vec aa = log(pp);
|  // Get the result back
|  NumericVector ans(p.length());
|  ans = aa;
|  // Set attributes
|  ans.attr("dim")      = p.attr("dim");
|  ans.attr("dimnames") = p.attr("dimnames");
|  return(wrap(ans));   
|  '  
| > library(inline)
| > loga <- cxxfunction(signature(pp_ = ""), src, plugin = "RcppArmadillo", verbose=F)
| > loga(pp)
|     B
| A            b1         b2
|   a1 -2.3025851 -0.9162907
|   a2 -0.9162907 -2.3025851
| 
| This works, but if anyone can spot a more elegant (fewer lines) way of doing it, I would be happy to know...

All untested and just ideas:

a) Just use Rcpp sugar if all you need is log() etc pp which is present in
   sugar; this should preserve attributes

b) First clone the source object to preserve names, dims, ...; then do
   transformation and just insert new values

c) If it walks and quacks like a Matrix, ... so use NumericMatrix which does
   have a dim attribute

Dirk

| 
| Best regards
| Søren
| 
| _______________________________________________
| Rcpp-devel mailing list
| Rcpp-devel at lists.r-forge.r-project.org
| https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com  


More information about the Rcpp-devel mailing list