inmybrain
inmybrain

Reputation: 386

Call a subset of a vector in Rcpp (not replacing elements)

I'd like to make a function that returns a subset of a vector. In R, it is

x <- 1:3 
x[2:3] # return 2nd, 3rd elements

My Rcpp code is as follows,

// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
using namespace Rcpp;

// [[Rcpp::export]]
Rcpp::List subset(arma::vec x){
  return List::create(Named("sub_x") = x.elem(seq(1,2)));
}

but it give me an error

no matching function for call to 'arma::Col<double>::elem(Rcpp::Range)'

I've seen many posts talking about replacing elements in a vector using .elem, but it is hard to find something fit to my question, as far as I know of.

Upvotes: 0

Views: 441

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368639

A couple of comments:

  1. You supply a vector. You want a vector. You wrote a function returning a List. Hm.

  2. The compiler tells you it does know how to stick Rcpp::Range into an Armadillo type. That is a good hint.

  3. Armadillo has this documented under element access and submatrix view.

So just write

// [[Rcpp::export]]
arma::vec mysubset(arma::colvec x) {
  return x.rows(1,2);
}

and you're done as seen here:

R> Rcpp::sourceCpp("~/tmp/so51138571.cpp")

R> x <- 1:3

R> mysubset(x)
     [,1]
[1,]    2
[2,]    3
R> 

This is likely also a duplicate of existing indexing question.

Upvotes: 3

Related Questions