How do classes and methods work in R and whats the most convenient way to use them? - r

I'm trying to do some object oriented programming in R. Im familiar with OOP syntax from other languages like Python and Java, but i don't understand how classes work in R.
I've found some examples are sources online but none of them are explained, its just raw code which seems to not make any sense.
Could you please tell me how a simple python class like the following can be written in R, with some explination:
class Num():
def __init__(self, number):
self.data = number
def print_number(self):
print(self.data)

Related

erf() and IntervalRootFinding

I realize this is a pretty niche problem, but I figure it's worth asking anyway.
I'm working on a program that does root-finding, and the function that it's trying to find a root for involves computing Fresnel integrals, which are implemented using erf(). I thought I'd try using the IntervalRootFinding package, but haven't gotten very far with it. I get a MethodError exception, which looks like:
MethodError: no method matching _erf(::Complex{IntervalArithmetic.Interval{Float64}})
Any advice?
IntervalArithmatic requires that your functions know how to work with intervals. Since erf is monotonic, you could define your own implimentation
using IntervalArithmatic
erf(x::Interval{T}) where T = Interval(prevfloat(erf(x.lo)), nextfloat(erf(x.hi)))

Exposing a C struct with Rcpp?

I am looking for advice on how to write a wrapper package for the GLFW C library using Rcpp.
I have already started, and I've managed to wrap a few simple functions from the GLFW library.
Now I was looking at the function glfwCreateWindow
:
GLFWwindow* glfwCreateWindow(int width,
int height,
const char* title,
GLFWmonitor* monitor,
GLFWwindow* share)
As can be seen from its prototype, it accepts these arguments that are pointers to structs. Because this function needs to be used by the user, these objects also have to be exposed to the user in R. I would like to expose these objects as S4 classed objects. I read the Rccp vignette on Rcpp Modules that looked very promising. However, I am not entirely sure how to apply them to C structs...?
From what I could find:
There is this similar question on SO: How to expose a C structure from C library to R with Rcpp, however it's been six years since this question has been posted so I'm wondering if there has been any update on this? This question is further expanded in this thread: http://lists.r-forge.r-project.org/pipermail/rcpp-devel/2013-July/006249.html;
I also found this example of an R package wrapping a C library in the Rcpp gallery: https://gallery.rcpp.org/articles/accessing-xts-api/, but unfortunately only functions are exposed using Modules, i.e., no C structs are exposed.
So my understanding right now is that I'll have to use the macro RCPP_EXPOSED_CLASS but I could not fully understand what it is doing.
Do you recommend creating C++ classes for all those C structs and then use Rcpp Modules to expose them?
Do you know of a package that does this in an idiomatic way that I could study from?
Thank you!
PS. Please do not flag this question as a duplicate immediately as there might had been recent developments.

Importing functions in R

In Python we have chance to import a certain function from a library with a command "import function from library as smth. Do we have something similar in R?
I know that we can call the function like "library::function()", my question mostly refers to the "as" part.
It is not common and not necessary to do this in R. The assignment operator <- can be used to give a new name to an existing function. For example, one could define a function that does exactly the same as lubridate's, year() function with:
asYear <- lubridate::year
One could argue that, by doing so, the year() function has been "imported" from the lubridate package and that it is now called asYear(). In fact, the new function does just the same (which is no surprise, simply because it is the same):
asYear(Sys.Date())
#[1] 2016
So it is possible to construct an analogy to "from package import as", but it is not a good idea to do this. Here are a few reasons I can think of:
Debugging a code where library functions have been renamed will be
much more difficult.
The documentation is not available for the renamed function. In this example, ?asYear won't work, in contrast to ?lubridate::year or library(lubridate); help(year).
The function is not only renamed but it is copied, which clutters the environment and is inefficient in terms of memory usage.
The maintenance of the code becomes unnecessarily difficult. If another programmer (or the original programmer a few years later) looks at a code containing such a redefinition of a function, it will be harder for her or him to understand what this function is doing.
There are probably more reasons, but I hope that this is sufficient to discourage the use of such a construction. Different programming languages have different peculiarities, and as a programmer it is necessary to adapt to them. What is common in Python can be awkward in R, and vice versa.
A simple and commonly used way to handle such a standard situation in R is to use library() to load the entire namespace of the package containing the requested function:
library (lubridate)
year(Sys.Date())
However, one should be aware of possible namespace clashes, especially if many libraries are loaded simultaneously. Different functions could be defined with the same name in different packages. A well-known example thereof are the contrasting implementations of the lag() function in the dplyr and stats package.
In such cases one can use the double colon operator :: to resolve the namespace that should be addressed. This would be similar to the use of "from" in the case of "import", but such a specification would be needed each time the function is called.
lubridate::year(Sys.Date())
#[1] 2016

Converting models in Matlab/R to C++/Java

I would like to convert an ARIMA model developed in R using the forecast library to Java code. Note that I need to implement only the forecasting part. The fitting can be done in R itself. I am going to look at the predict function and translate it to Java code. I was just wondering if anyone else had been in a similar situation before and managed to successfully use a Java library for the same.
Along similar lines, and perhaps this is a more general question without a concrete answer; What is the best way to deal with situations where in model building can be done in Matlab/R but the prediction/forecasting needs to be done in Java/C++? Increasingly, I have been encountering such a situation over and over again. I guess you have to bite the bullet and write the code yourself and this is not generally as hard as writing the fitting/estimation yourself. Any advice on the topic would be helpful.
You write about 'R or Matlab' to 'C++ or Java'. This gives 2 x 2 choices which is too many degrees of freedom for my taste. So allow me to concentrate on C++ as the target.
Let's consider a simpler case: Prototyping in R, and deploying in C++. If and when the R package you use is actually implemented in C or C++, this becomes pretty easy. You "merely" need to disentangle the routine you are after from its other dependencies (header files, defines, data structures, ...) and provide it with the data and parameters needed. I have done that in the past for production systems.
Here, you talk about the forecast package. This happens to depend on the RcppArmadillo package which itself brings the nice Armadillo C++ library to R. So chances are you can in fact re-write this as a self-contained unit.
Armadillo is also interesting when you want to port Matlab to C++ as it is written to help with exactly that task in mind. I have ported some relatively extensive Matlab code to C++ and reaped a substantial speed gain.
I'm not sure whether this is possible in R, but in Matlab you can interact with your Matlab code from Java - see http://www.cs.virginia.edu/~whitehouse/matlab/JavaMatlab.html. This would enable you to leave all the forecasting code in Matlab and have e.g. an interface written in Java.
Alternatively, you might want to have predictive code written in Java so that you can produce a model and then distribute a program that uses the model without having a dependency on Matlab. The Matlab compiler maybe be useful here, but I've never used it.
A final simple way of interacting messily between Matlab and Java would be (on linux) using pseudoterminals where you would have a pty/tty pair to interface Java and Matlab. In this case you would send data from Java to Matlab, and have Matlab return the forecasting results. I expect this would also work in R, but I don't know the syntax.
In general though, reimplementing the code is a decent solution and probably quicker than learning how to interface java+matlab or create Matlab libraries.
Some further information on the answer given by Richante: Matlab has some really nice capabilities for interop with compiled languages such as C/C++, C#, and Java. In your particular case you might find the toolbox Matlab Builder JA to be particularly relevant. It allows you to export your Matlab code directly to Java, meaning you can directly call code that you've constructed during your model-building phase in Matlab from Java.
More information from the Mathworks here.
I am also concerned with converting "R to Java" so will speak to that part.
As Vincent Zooneykind said in his comment - the PMML library in R makes sense for model export in general but "forecast" is not a supported library as of yet.
An alternative is to use something like https://www.opencpu.org/ to make a call to R from your java program. It surfaces the R code on a http server. Can then just call it with parameters as with a normal http call and return what is neede using java.net.HttpUrlConnection or a choice of http libraries available in Java.
Pros: Separation of concerns, no need to re-write the R code
Cons: Invoking an R server in your live process so need to make sure that is handled robustly

Calling Clojure from within R?

Is there any link between R and Clojure?
I am aware of Incanter, but am ideally looking for an R package for Clojure
or any future plans for one, in order to call clojure from within R.
Clojure compiles to Java byte code, so you should be able to do what you want using rJava. The slightly ugly part would be figuring out what the method signatures are, since rJava requires the JNI-style method signature.
Check out Rincanter.

Resources