user_012314112 - 3 days ago 3x

R Question

my question is trivial, but I'm new with RCPP and still have not mastered. I wanted to make a function that given a categorical vector and two integers returns the subset of vector content between the two integers. You know, ["A","B","C","D] and 1 and 2, returns me ["B","C"].

I did the next code but doesn't work.

`// [[Rcpp::export]]`

Rcpp::StringVector Segment(Rcpp::StringVector x, int start, int end) {

Rcpp::StringVector s(end-start+1);

for(int i=start; i <= end; i++){

s[i]=x[i];

}

return(s);

}

Answer

Try to use `CharacterVector`

. The solution could be like this.

```
// [[Rcpp::export]]
CharacterVector Segment( CharacterVector x, int start, int end){
CharacterVector r(end-start+1);
int ind=0;
for( int i=0; i<=r.size(); i++){
if((i>=start) & (i<=end)){
r[ind]=x[i];
ind+=1;
}
}
return(r);
}
```

Source (Stackoverflow)

Comments