How to get a length one sub-vector of a NumericVector in Rcpp
02:39 31 Oct 2025

How can I get a length one sub-vector of a NumericVector in Rcpp. Similar to the drop=FALSE argument in [ in R. The only solution I found so far is to use a length 1 NumericVector as an auxillary variable and assign to its first element.

This is especially relevant when passing sub vectors as function arguments to other functions. The need to define an additional variable and do an additional assignment makes the code less readable and is risky in terms of errors introduced by getting the length of the auxillary variable wrong.

edit: (the old example was too simple and did not reproduce the issue)

library("Rcpp")

sourceCpp(code='
#include 
using namespace Rcpp;

NumericVector test2(NumericVector x){
  return(x);
}

// [[Rcpp::export]]
NumericVector test3(){
  NumericVector vec = {1,2,3};
  int i=0;
  NumericVector res;
  res = test2(vec[i]);
  return(res);
}

// [[Rcpp::export]]
NumericVector test4(){
  NumericVector vec = {1,2,3};
  int i=0;
  NumericVector res;
  res = test2(vec[Range(i,i)]);
  return(res);
}
')

test3()
# [1] 0
test4()
# [1] 1

packageVersion("Rcpp")
# [1] ‘1.1.0’

R.version.string
# [1] "R version 4.4.3 (2025-02-28 ucrt)"

Old example before edit:

NumericVector vec = {1,2,3};
NumericVector v1 = NumericVector(1);
double v2;

# works
v2=vec[0];
v1[0]=v2;

# does not work
v1=vec[0];
r rcpp