No sugar function for apply
. The easiest way to do what you want is to call as<double>
, i.e.:
output[i]=as<double>(f(x(i,_)));
You can also insert this into a type that calls for you as
, for example:
template <typename T>
class F {
public:
F( SEXP f_) : f(f_){}
inline T operator()(NumericVector x){
return as<T>(f(x)) ;
}
private:
Function f ;
} ;
so you can:
NumericVector apply_cpp(NumericMatrix x,int dim,F<double> f){
if(dim==1){
NumericVector output(x.nrow());
for(int i=0;i<x.nrow();i++){
output[i]=f(x(i,_));
}
return output ;
}
else {
NumericVector output(x.ncol());
for(int i=0;i<x.ncol();i++){
output[i]=f(x(_,i));
}
return output ;
}
}
F
, NumericVector
, double
. . - ( ++ 11):
template <typename T, typename... Args>
class F {
public:
F( SEXP f_) : f(f_){}
inline T operator()(Args... args){
return as<T>(f(args...)) ;
}
private:
Function f ;
} ;
:
NumericVector apply_cpp(NumericMatrix x,int dim,F<double,NumericVector> f){