从列表Rcpp中检索对象

问题描述 投票:1回答:1

我是Rcpp的新手,我正在努力解决它。我有一个函数返回一个包含2个对象的列表:来自向量的max和argmax。我想在另一个函数中从该列表中仅检索最大值或仅检索argmax。我怎样才能做到这一点?下面是一个例子:

#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);
}   
r list rcpp
1个回答
2
投票

在第二个示例中,您可以简单地调用原始函数并将其分配给List,其元素可以通过名称(或位置)检索:

#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)
*/

输出:

> set.seed(42)

> x <- runif(100)

> max_argmax_cpp(x)
$Max
[1] 0.7439746

$Argmax
[1] 99


> max_only(x)
[1] 0.7439746
© www.soinside.com 2019 - 2024. All rights reserved.