我希望使用Rcpp访问整数向量中的第二个唯一元素的值,但得到长度等于整数向量中第二个项的值的零向量。我做错了什么?
require(Rcpp)
cppFunction("NumericVector test(IntegerVector labelling1) {
IntegerVector lvls = unique(labelling1);
return(lvls[1]);
}")
test(1:5)
#[1] 0 0发布于 2014-10-21 19:49:06
实际上,这里有一个单独的问题:您试图从一个NumericVector构建一个int,并且Rcpp执行以下操作:
2,NumericVector被构造为NumericVector(2);即长度为2的NumericVector。如果您真正想要的是表示该索引上的值的IntegerVector,则必须编写:
IntegerVector test(IntegerVector labelling1) {
IntegerVector lvls = unique(labelling1);
return IntegerVector::create(lvls[1]);
}或者您也可以使用Rcpp属性(它为您自动处理从int到IntegerVector的转换):
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
int test(IntegerVector labelling1) {
IntegerVector lvls = unique(labelling1);
return lvls[1];
}
/*** R
test(1:5)
*/发布于 2014-10-21 07:57:38
Subset砂糖需要一个IntegerVector作为索引(http://gallery.rcpp.org/articles/subsetting/)。如果您想模仿R的unique函数,您需要进行一些额外的更改:
cppFunction("IntegerVector test(IntegerVector labelling1, int i) {
// get sorted unique values
IntegerVector lvls = sort_unique(labelling1);
// get unique values in order of occurence
IntegerVector lvls1 = lvls[match(lvls, labelling1) - 1];
return(lvls1[IntegerVector::create(i - 1)]);}")
test(c(5:1, 1L), 2)
#[1] 4https://stackoverflow.com/questions/26477803
复制相似问题