从列表 Rcpp 中检索对象
Retrieve object from a list Rcpp
我是 Rcpp 的新手,我正在为它苦苦挣扎。我有一个函数 return 一个包含 2 个对象的列表:来自向量的 max 和 argmax。我想在另一个函数中从该列表中仅检索 max 或仅检索 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
我是 Rcpp 的新手,我正在为它苦苦挣扎。我有一个函数 return 一个包含 2 个对象的列表:来自向量的 max 和 argmax。我想在另一个函数中从该列表中仅检索 max 或仅检索 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