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.
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. 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
. Do not forget to free it.
Very good useful manual is here http://adv-r.had.co.nz/C-interface.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.