A.T
A.T

Reputation: 13

Retrieve object from a list Rcpp

I'm new to Rcpp and I'm struggling with it. I have a function that return a list with 2 objects: max and argmax from a vector. I would like to retrieve only max or only argmax from that list in another function. How can I do that? Below an example:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List max_argmax_cpp(NumericVector x){
  double max = x[0];
  int argmax = 0 + 1;
  for(int i = 1; i < x.length(); i++){
    if(x[i]>x[i-1]){
      max = x[i];
      argmax = i+1;
    }
  }
  List Output;
  Output["Max"] = max;  
  Output["Argmax"] = argmax;
  return(Output);
}

// [[Rcpp::export]]
int max_only(NumericVector x){
  int max = **only max from max_argmax_cpp(x)**;
  return(max);
}   

Upvotes: 1

Views: 535

Answers (1)

Ralf Stubner
Ralf Stubner

Reputation: 26823

In your second example you can simply call your original function and assign it to a List, whose elements can the be retrieved by name (or position):

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List max_argmax_cpp(NumericVector x){
  double max = x[0];
  int argmax = 0 + 1;
  for(int i = 1; i < x.length(); i++){
    if(x[i]>x[i-1]){
      max = x[i];
      argmax = i+1;
    }
  }
  List Output;
  Output["Max"] = max;  
  Output["Argmax"] = argmax;
  return(Output);
}

// [[Rcpp::export]]
double max_only(NumericVector x){
  List l = max_argmax_cpp(x);
  double max = l["Max"];
  return(max);
} 
/*** R
set.seed(42)
x <- runif(100)
max_argmax_cpp(x)
max_only(x)
*/

Output:

> set.seed(42)

> x <- runif(100)

> max_argmax_cpp(x)
$Max
[1] 0.7439746

$Argmax
[1] 99


> max_only(x)
[1] 0.7439746

Upvotes: 2

Related Questions