[英]How to return a C++ object (double *) to R as SEXP?
I have to write a linear regression program and invoke it using R. This is my code.It is not able to return back theta as SEXP.我必须编写一个线性回归程序并使用 R 调用它。这是我的代码。它无法将 theta 作为 SEXP 返回。
SEXP reg(Rcpp::NumericVector x,Rcpp::NumericVector y){
int i,n1,n2;
n1=x.size();
n2=y.size();
if(n1!=n2)
cout<<"Error";
else{
double wx[n1], wy[n1];
for(i=0;i<n1;i++){
wx[i]=x[i];
wy[i]=y[i];
}
int iterations=1500;
//default learning rate;
double alpha=0.01;
double *theta = new double[2];
double *J = new double[iterations];
theta = gradient_descent(wx,wy, alpha, iterations, J, n1,theta);
return(theta);
}
}
It gives error:Cannot convert 'double *' to 'SEXP' in return.它给出了错误:无法将 'double *' 转换为 'SEXP' 作为回报。 I want some solution for this.
我想要一些解决方案。
You function is improper.你的功能不正常。 Try like bellow (not tested):
尝试如下(未测试):
SEXP reg(Rcpp::NumericVector x,Rcpp::NumericVector y){
int i,n1,n2;
SEXP out = PROTECT(allocVector(REALSXP, 2));
n1=x.size();
n2=y.size();
if(n1!=n2)
cout<<"Error";
else{
double wx[n1], wy[n1];
for(i=0;i<n1;i++){
wx[i]=x[i];
wy[i]=y[i];
}
int iterations=1500;
//default learning rate;
double alpha=0.01;
double *theta = REAL(out);
double *J = new double[iterations];
theta = gradient_descent(wx,wy, alpha, iterations, J, n1,theta);
}
UNPROTECT(1);
return(out);
}
I do not know your function gradient_descent
and who should care about freeing resource pointed by J
.我不知道你的函数
gradient_descent
以及谁应该关心释放J
指向的资源。 Do not forget to free it.不要忘记释放它。
Very good useful manual is here http://adv-r.had.co.nz/C-interface.html非常有用的手册在这里http://adv-r.had.co.nz/C-interface.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.