Shubham Gupta
Shubham Gupta

Reputation: 660

Create NumericMatrix from NumericVector

Is there a way to create NumericMatrix from NumericVectors? Something like this:

Rcpp::cppFunction("NumericMatrix f(){
    NumericVector A(10, 2.0);
    NumericVector B(10, 1.0);
        return NumericMatrix(10,2,C(A,B)); //ERROR
}")

> f()

Upvotes: 1

Views: 87

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368509

Sure. There is for example cbind.

Code

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericMatrix makeMatrix(Rcpp::NumericVector a, Rcpp::NumericVector b) {
  return Rcpp::cbind(a, b);
}

/*** R
a <- c(1,2,3)
b <- c(3,2,1)
makeMatrix(a,b)
*/

Output

> Rcpp::sourceCpp("~/git/stackoverflow/65538515/answer.cpp")

> a <- c(1,2,3)

> b <- c(3,2,1)

> makeMatrix(a,b)
     [,1] [,2]
[1,]    1    3
[2,]    2    2
[3,]    3    1
> 

Upvotes: 3

Related Questions