gpt4 book ai didi

r - 如何防止 Rcpp 评估 'call' 对象

转载 作者:行者123 更新时间:2023-12-01 00:42:16 26 4
gpt4 key购买 nike

我需要简单的包装器来从 Rcpp 代码中序列化任意 R 对象。下面是我的代码的简化版本:

// [[Rcpp::export]]
Rcpp::RawVector cpp_serialize(RObject x) {
Rcpp::Function serialize = Rcpp::Environment::namespace_env("base")["serialize"];
return serialize(x, R_NilValue);
}

这很好用,但是我发现对于类 call 的对象。调用在被序列化之前被评估。我怎样才能防止这种情况发生?我只想模仿 serialize()在 R。
# Works as intended
identical(serialize(iris, NULL), cpp_serialize(iris))

# Does not work: call is evaluated
call_object <- call("rnorm", 1000)
identical(serialize(call_object, NULL), cpp_serialize(call_object))

更新 :我有一个解决方法(见下文),但我仍然对适当的解决方案非常感兴趣。
Rcpp::RawVector cpp_serialize(RObject x) {
Rcpp::Environment env;
env["MY_R_OBJECT"] = x;
Rcpp::ExpressionVector expr("serialize(MY_R_OBJECT, NULL)");
Rcpp::RawVector buf = Rcpp::Rcpp_eval(expr, env);
}

最佳答案

我认为您在 Rcpp::Function 中发现了意外行为。类(class)。一个 MRE:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
RObject cpp_identity(RObject x) {
Rcpp::Function identity("identity");
return identity(x);
}

/*** R
quoted <- quote(print(1));
identity(quoted)
cpp_identity(quoted)
*/


> quoted <- quote(print(1));

> identity(quoted)
print(1)

> cpp_identity(quoted)
[1] 1
[1] 1

发生这种情况是因为 Rcpp 在幕后有效地执行了此评估:
Rcpp_eval(Rf_lang2(Rf_install("identity"), x))

这基本上就像
eval(call("identity", quoted))

但调用对象不受评估的“保护”。

关于r - 如何防止 Rcpp 评估 'call' 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36808581/

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