0

I am converting this R function into C++ function using Rcpp package. However, since rdiscrete() function is from e1071 package, I am struggling to loading the existing R package and calling the functions from this package.

R function (works fine):

library(e1071)
signR <- function(x) {
if (x >= 0) {
rdiscrete(10,c(0.2,0.8),c(5,6))
 } else {
rdiscrete(10,c(0.2,0.8),c(1,2))
 }
}
## Example
signR(2)

Rcpp version (error pointed to rdiscrete function):

library(Rcpp)
cppFunction('int signC(int x) {
if (x >= 0) {
return rdiscrete(10,c(0.2,0.8),c(5,6));
 } else {
return rdiscrete(10,c(0.2,0.8),c(1,2));
 }
}')

I appreciate any replies in advance!

Joanna
  • 663
  • 7
  • 21
  • Besides the duplicate, what are you trying to achieve? Calling the function from C++ instead of R won't speed up the code at all. – Ralf Stubner Nov 29 '18 at 22:56
  • In addition to @RalfStubner 's great points about the dupe (there are things there you need to do but aren't to make the R function accessible) and this not speeding up your code at all, there are other things to note: `c()` is not how you create `NumericVector`s; you need `NumericVector::create()`; `int` should not be the return type, but `IntegerVector`; (1/2) – duckmayr Nov 29 '18 at 23:18
  • 2
    And most importantly, according to the help file for `rdiscrete()`, "The random number generator is simply a wrapper for sample and provided for backwards compatibility only," so you'd be better off using [RcppArmadillo::sample()](http://gallery.rcpp.org/articles/using-the-Rcpp-based-sample-implementation/) (2/2) – duckmayr Nov 29 '18 at 23:18
  • 1
    Good job looking at what the function does, @duckmayr. As I recently learned there is also [`Rcpp::sample()`](https://github.com/RcppCore/Rcpp/blob/master/inst/include/Rcpp/sugar/functions/sample.h). – Ralf Stubner Nov 29 '18 at 23:29
  • Thanks for all suggestions. I will check it out. @RalfStubner, thanks for sharing your thoughts, I am developing some R functions which require to use loops, and using R is very slow so I converted the loops part into C++. However, I was stuck about `rdiscrete()` function so I made up a quick demo example here. – Joanna Nov 30 '18 at 00:22

0 Answers0