[Rcpp-devel] Rccp code with vector and matrix inputs and matrix output

Dirk Eddelbuettel edd at debian.org
Fri Mar 28 12:25:50 CET 2014


On 28 March 2014 at 10:30, Petre Caraiani wrote:
| Hello,
| The following code works well in R:
| attach(dataqtr)
| 
| dataqtr <- data.table(dataqtr)
| setkeyv(dataqtr,c("gvkey","qtr"))
| 
| vec_growth <- data.frame(0,0,0,0,0,0,0,0,0,0,0,0,0)
| vec_eps    <- data.frame(0,0,0,0,0,0,0,0,0,0,0,0,0)
| 
| T <- 15
| 
| for (i in 1:nrow(dataqtr)) {
|   vec_growth[i,] <- ( dataqtr[i,LTG] * exp(1:(T-2)/(T-1)*log( dataqtr
| [i,meanLTG] / dataqtr[i,LTG] )))
|  
| }
| 
| 
| However I am not able to reproduce it using the following Rccp code:
| 
| a<- dataqtr[,LTG]
| b<- dataqtr[,meanLTG]
| 
| src <-'
|  Rcpp::NumericVector a(aa);
|  Rcpp::NumericVector b(bb);
|  Rcpp::NumericMatrix Am (A);
|  int n = a.size();
|  int m = b.size();
|  int T=15;
|  
|  int nrows = Am.nrow();
|  int ncol  = Am.ncol();
|  
|      for (int ii = 1; ii < nrows; ii++) {
|         for (int jj = 1; jj<ncol; jj++)  {
|         Am[ii,jj] =  a[jj] * exp(jj/(T-1)*log( b[jj] / a[jj] ));
|         }}
| return Am;
| '
| fun <- cxxfunction(signature(aa="numeric", bb="numeric",A="numeric"), body =
| src, plugin="Rcpp")
| 
| A<-matrix(data=NA,nrow=100,ncol=13)
| fun(a,b,A)
| 
| I don't understand the error.

What is the error you are getting and do not understand? Can you share it?

Is it __build-time__ ?  Is it __run-time__ ?

At a first glance both your for loops are wrong as indices in C and C++ have
to go from 0 to n-1, not 1 to n.

Dirk

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


More information about the Rcpp-devel mailing list