gpt4 book ai didi

c++ - 我不明白 Rcpp 中的这种行为

转载 作者:行者123 更新时间:2023-11-28 00:23:08 25 4
gpt4 key购买 nike

我想使用 Rcpp 访问整数 vector 中第二个唯一元素的值,但我得到的是一个零 vector ,其长度等于整数 vector 中第二项的值。我做错了什么?

require(Rcpp)
cppFunction("NumericVector test(IntegerVector labelling1) {
IntegerVector lvls = unique(labelling1);
return(lvls[1]);
}")

test(1:5)
#[1] 0 0

最佳答案

这里实际上有一个单独的问题:您正在尝试从 int 构造一个 NumericVector,而 Rcpp 执行以下操作:

  1. 您的函数正在返回整数值 2
  2. NumericVector 构造为 NumericVector(2);即,长度为 2 的 NumericVector

如果您真正想要的是一个表示该索引值的IntegerVector,您必须这样写:

IntegerVector test(IntegerVector labelling1) {
IntegerVector lvls = unique(labelling1);
return IntegerVector::create(lvls[1]);
}

或者您也可以使用 Rcpp 属性(自动为您处理从 intIntegerVector 的转换):

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int test(IntegerVector labelling1) {
IntegerVector lvls = unique(labelling1);
return lvls[1];
}

/*** R
test(1:5)
*/

关于c++ - 我不明白 Rcpp 中的这种行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26477803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com