我是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);
}
在第二个示例中,您可以简单地调用原始函数并将其分配给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