[英]I don't understand this behaviour in Rcpp
I would like to access the value of the second unique element in an integer vector using Rcpp, but instead I get a vector of zeros that is equal in length to the value of the second item in the integer vector. 我想使用Rcpp访问整数向量中的第二个唯一元素的值,但是我得到的是零向量,其长度等于整数向量中第二项的值。 What am I doing wrong?
我究竟做错了什么?
require(Rcpp)
cppFunction("NumericVector test(IntegerVector labelling1) {
IntegerVector lvls = unique(labelling1);
return(lvls[1]);
}")
test(1:5)
#[1] 0 0
There is actually a separate issue here: you are trying to construct a NumericVector
from an int
, and Rcpp does the following: 实际上,这里存在一个单独的问题:您尝试从
int
构造NumericVector
,而Rcpp执行以下操作:
2
is being returned by your function, 2
, NumericVector
is constructed as NumericVector(2)
; NumericVector
构造为NumericVector(2)
; ie, a NumericVector
with length 2. NumericVector
。 If what you really want is an IntegerVector
representing the value at that index, you must write: 如果您真正想要的是一个
IntegerVector
表示该索引处的值,则必须编写:
IntegerVector test(IntegerVector labelling1) {
IntegerVector lvls = unique(labelling1);
return IntegerVector::create(lvls[1]);
}
Or you could also do, using Rcpp attributes (which handles conversion from int
to IntegerVector
automatically for you): 或者,您也可以使用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)
*/
Subsetting sugar expects an IntegerVector
as index ( http://gallery.rcpp.org/articles/subsetting/ ). 子集糖期望将
IntegerVector
作为索引( http://gallery.rcpp.org/articles/subsetting/ )。 If you want to mimic R's unique
function you need some additional changes: 如果要模仿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] 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.