如何保护 R 中的矩阵不被 Rcpp 更改? [英] How can I protect a matrix in R from being altered by Rcpp?

查看:30
本文介绍了如何保护 R 中的矩阵不被 Rcpp 更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个包含两个 Rcpp 函数的包.第一个函数用于创建一个矩阵,该矩阵将被第二个函数多次使用.在调用这两个函数之间,矩阵存储在 R 的全局环境中.

I am making a package containing two Rcpp functions. The first function is used for creating a matrix that will be used several times by the second function. The matrix is stored in R's global environment between calls to the two functions.

M <- myFirstRcpp(X)
P <- mySecondRcpp(M)

根据输入参数,第二个函数将对输入矩阵(由第一个函数创建)进行更改,然后从中计算向量(aFunctionmySecondRcpp()):

Depending on input parameters the second function will make changes to the input matrix (created by the first function) before calculating a vector from it (aFunction is the C++ inside mySecondRcpp()):

IntegerVector aFunction( SEXP Qin, SEXP param ) {
    NumericMatrix Q(Qin);
    // Some changes made to Q
    ...
    // return a vector generated from Q
}

我的问题是对第二个 Rcpp 函数内的 Q 矩阵所做的更改也会影响驻留在 R 全局环境中的矩阵 (M) 的副本.

My problem is that the changes done to the Q matrix inside the second Rcpp function also affect the copy of the matrix (M) residing in R's global environment.

如何在没有太多开销的情况下防止 Rcpp 改变 R 的全局环境?

How can I prevent Rcpp from altering the global environment of R without too much overhead?

注意:M 矩阵的大小约为 2000x65000.问题出现在 R 3.0.2 和 Rcpp 0.10.6 在 Windows 和 Linux 上的 32 位和 64 位 R.

Notes: The M matrix is ~2000x65000 in size. The problem occurs with R 3.0.2 and Rcpp 0.10.6 on Windows and Linux in 32 and 64 bit R.

推荐答案

这是一个已知且记录在案的功能.我们正在通过接口从 R 调用

That is a known and documented feature. We are being called from R via the interface

  SEXP somefunction(SEXP a, SEXP b, ...)

所以指针被传递并且对Q的改变影响外部对象.这是一件好事,因为它使调用速度非常快——没有副本.

so a pointer is being passed and changes to Q affect the outer object. That is a good thing as it makes the calls very fast -- no copies.

如果您想要不同的实例,请使用 clone() 方法,如

If you want distinct instances, use the clone() method as in

  NumericMatrix Q = clone(Qin);

这篇关于如何保护 R 中的矩阵不被 Rcpp 更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆