Rcpp:与代理模型的行为不一致 [英] Rcpp: Inconsistent behavior with proxy model
问题描述
这篇帖子讨论了参数代理模型的一些问题通过 Rcpp.但是,当我实现此功能时:
This post discusses some issues with the proxy model for parameter passing in Rcpp. However, when I implemented this function:
// [[Rcpp::export]]
void test_size(NumericVector test){
NumericVector test2(test);
NumericVector test3 = NumericVector::create(1,1,1,1,1);
test2 = test3;
Rf_PrintValue(test);
}
我们得到:
> temp = c(2,2,2,2)
> test_size(temp)
[1] 2 2 2 2
所以问题是上一篇文章和这本book 在这种情况下说test2
应该是一个指向 R
底层 SEXP
对象的指针.但是,当我们分配 test2 = test3
时,这不适用于 test
,因为 test
NumericVector
保持不变.
So the problem is that the previous post and this book say that in this case test2
should be a pointer to the underlying SEXP
object from R
. However, when we assigned test2 = test3
, this didn't apply to test
because the test
NumericVector
remained unchanged.
更新
我正在添加一个示例,其中我认为分配没有像 Dirk 建议的那样工作,但当然我可能会误解这个问题.
I am adding an example where I think assignment isn't working as Dirk suggested, but of course I could be misunderstanding the problem.
所以假设我有以下功能:
So suppose I have the following function:
// [[Rcpp::export]]
NumericVector testing(){
NumericMatrix mat(3,3);
mat.row(0) = NumericVector::create(1,1,1);
mat.row(1) = NumericVector::create(1,1,1);
mat.row(2) = NumericVector::create(2,2,2);
NumericVector test;
NumericVector test2;
for (int i = 0; i < mat.nrow(); i++){
test = mat.row(i);
if (test[0] == 1){
test2 = test;
}
}
return test2;
}
这个函数应该输出1,1,1
,但它输出的是2,2,2
.但是,当我用 test2 = clone(test)
替换 test2 = test
时,我得到了正确的输出.所以我想知道为什么我会得到这种行为,即使这只是 Dirk 建议的分配?
This function is supposed to output 1,1,1
, but instead it outputs 2,2,2
. However when I replace test2 = test
with test2 = clone(test)
then I get the correct output. So I was wondering why am I getting this behavior even though this is just assignment as Dirk suggested?
推荐答案
当您查看以下修改后的程序中的所有三个时,我会变得更容易:
I gets easier when you look at all three as in the modified program below:
R> testvecs(c(2,2,2,2))
$test
[1] 2 2 2 2
$test2
[1] 1 1 1 1 1
$test3
[1] 1 1 1 1 1
R>
(现在完成的)代码在哪里
where the (now complete) code is
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List testvecs(NumericVector test){
NumericVector test2(test);
NumericVector test3 = NumericVector::create(1,1,1,1,1);
test2 = test3;
return List::create(Named("test") = test,
Named("test2") = test2,
Named("test3") = test3);
}
/*** R
testvecs(c(2,2,2,2))
*/
所以:
test
传入且未更改,结果并不意外test2
被创建,然后覆盖test3
刚刚创建,并按预期出现test2
被指定为与test3
相同,并且确实如此.
test
is incoming and unaltered, no surprise on the outcometest2
is created and then overwrittentest3
is freshly created, and comes out as expectedtest2
is assigned to be the same astest3
, and it is.
我发现这里没有任何不一致之处.
I see no inconsistency here.
这篇关于Rcpp:与代理模型的行为不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!