1

I am mainly R user, but I would like to learn Rcpp to improve my coding(speed). So I start out playing around with C++ and Rcpp, I thought I’d just try to write the following simple function which takes the row of matrix, (i.e first row) and deduct a vector from it (m[1,]-vec).

I know this sound silly and simple but I am not able to get it work.

code <- '
arma::mat beta = Rcpp::as(beta_);
arma::vec y = Rcpp::as(y_);
arma::rowvec S= beta.row(0);

arma::vec d = S - y;
return Rcpp::wrap(d);
'
fun <- cxxfunction(signature(beta_ ="matrix",y_="numeric"),code, plugin="RcppArmadillo")
m <- matrix(1:9,3)
vec <- c(1,2,5)
fun(m,vec)
Error in fun(m, vec) :

in R this wil be done as,
m[1,]-vec
0 2 2

4

1 回答 1

3
library(RcppArmadillo)
library(inline)
code <- '
arma::mat beta = Rcpp::as<arma::mat>(beta_);
arma::rowvec y = Rcpp::as<arma::rowvec>(y_);
arma::rowvec S= beta.row(0);
arma::rowvec d = S - y;
return Rcpp::wrap(d);
'
fun <- cxxfunction(signature(beta_ ="matrix",y_="numeric"),code, plugin="RcppArmadillo")
m <- matrix(1:9,3)
vec <- c(1,2,5)
fun(m,vec)
于 2012-02-09T04:03:42.367 回答