如何在Rcpp中乘以S4对象?缺少运算符定义

问题描述

描述错误 如何在 Rcpp 函数中使用 S4 对象?在我的示例中,S4 对象是 CVXR 包中的一个变量。

我在获取 cpp 文件时出现以下错误 这意味着乘法运算符“*”没有为 S4 对象和双对象定义。但这在 R 文件中是可以的。

- no match for 'operator*' (operand types are 'Rcpp::S4' and 'Rcpp::traints::storage_type<14>::type {aka double}')

复制

以下是我想使用 Rcpp 加速的原始 R 代码。它运行良好,没有错误

library('CVXR',warn.conflicts = T)

# Original R code,but two layer for loop is very slow. Thus I decide put for loop in C++ scipt.
# The original R code works good without error.
W = matrix(runif(100),10,10)
y = runif(10)
x = runif(10)
  
beta_k = Variable(1) #variable
L = 0


for(i in 1:(10-1)){ # time consuming!!!
  for(j in (i+1):10)
    L = L + W[i,j] * (y[i]-y[j] + beta_k*(x[j]-x[i]) )^2
}

obj = Minimize(L)
problem = Problem(obj)
result = solve(problem)
result$getValue(beta_k)

以下是新的 R 代码,其中 'cal_eqn' 替换了 for-loop 部分。 'cal_eqn' 函数在下面的 cpp 文件中声明。

## The below is R code which using a function in C++ file.
library(Rcpp) # load Rcpp first
# source C++ file in order to loading the function.
sourceCpp("cal_L.cpp")  #this line will cause error!!!

W = matrix(runif(100),10)
y = 21:30
x = 41:50

beta_k = Variable(1)
L = 0

# use this function to replace the for-loop.
L = cal_eqn(L,x,y,W,beta_k) # this line will also cause error!!!

obj = Minimize(L)
problem = Problem(obj)
result = solve(problem)
beta[k] = result$getValue(beta_k)

以下是 cal_L.cpp 文件

// create a new file and copy below code into it. Rename this file as 'cal_L.cpp'.
#include <Rcpp.h>
using namespace Rcpp;

// below is for-loop in R file.
// for(i in 1:(10-1)){ # time consuming!!!
//   for(j in (i+1):10)
//     L = L + W[i,j] * (y[i]-y[j] + beta_k*(x[j]-x[i]) )^2
// }

// [[Rcpp::export]]
double cal_eqn(double L,NumericVector x,NumericVector y,NumericMatrix W,S4 beta_k) {
  int len = 10;
  for(int i= 0; i<len-1; i++){
    for(int j = i+1; j<len; j++){
      L = L + W(i,j) * ( y(i)-y(j) + beta_k*(x(j)-x(i)) ) * ( y(i)-y(j) + beta_k*(x(j)-x(i)) );
      //int test = W(i,j-1) * ( y(i)-y(j) + (x(j)-x(i)) ) * ( y(i)-y(j) + (x(j)-x(i)) ); // This line prove there is NO other issue except the S4 operator not defined.
    }
  }
  
  return L;
}

预期行为搜索了一些关于 Rcpp 的教程。要使用 S4 对象,我们应该在 S4 对象中声明确切的插槽。对于 CVRX 包,变量有很多槽。我应该使用哪个插槽或我可以尝试其他见解?提前致谢。

版本

> sessionInfo()
R version 3.6.0 (2019-04-26)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19041)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  Grdevices utils     datasets  methods   base     

other attached packages:
[1] Rcpp_1.0.6

loaded via a namespace (and not attached):
[1] compiler_3.6.0

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)