Reputation: 15
Original R function:
psiBiSquare<-function(r,c){
true<-abs(r)<=c
false<-abs(r)>c
psi<-true*(r*(1-(r/c)^2)^2)+false*0
return(psi)
}
I am replacing this with a faster Rcpp implementation below:
#include <Rcpp.h>
#include <math.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector psiBS_rcpp(NumericVector r, double c) {
int n =r.size();
NumericVector y = clone(r);
for(int i=0;i<n;i++){
if(abs(r[i])<=c){
y[i]=(r*pow(1-pow(r/c,2),2));
}
else{
y[i]=0;
}
}
return y;
}
The error message is "cannot convert rcpp::sugar::" What am I doing wrong?
Upvotes: 1
Views: 110
Reputation: 368509
Couple of things:
You have really poor code formatting. There is no extra fee on spaces. Use them.
You are undecided about r
and use it at the same time as a vector, and its elements as a scalar. Your right hand side expression is vectorized, yet you try to assign to a scalar y[i]
.
Improved / corrected source file:
#include <Rcpp.h>
#include <math.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector psiBS_rcpp(NumericVector r, double c) {
int n = r.size();
NumericVector y = clone(r);
for (int i=0; i<n; i++) {
if (abs(r[i]) <=c ) {
y[i] = (r[i]*pow(1-pow(r[i]/c,2),2));
}
else{
y[i]=0;
}
}
return y;
}
/*** R
psiBiSquare <- function(r,c) {
true <- abs(r) <= c
false <- abs(r) > c
psi <- true * (r*(1-(r/c)^2)^2) + false*0
return(psi)
}
r <- seq(-3,3)
c <- 1.5
psiBiSquare(r, c)
psiBS_rcpp(r, c)
*/
Running it:
R> sourceCpp("/tmp/ij.cpp")
R> psiBiSquare <- function(r,c) {
+ true <- abs(r) <= c
+ false <- abs(r) > c
+ psi <- true * (r*(1-(r/c)^2)^2) + false*0
+ return(psi)
+ }
R> r <- seq(-3,3)
R> c <- 1.5
R> psiBiSquare(r, c)
[1] 0.000000 0.000000 -0.308642 0.000000 0.308642 0.000000 0.000000
R> psiBS_rcpp(r, c)
[1] 0.000000 0.000000 -0.308642 0.000000 0.308642 0.000000 0.000000
R>
Upvotes: 3