Calling an R function

R is an open source programming language commonly used for data analysis. This page describes how to call an existing R function from a model running in the Analytica Enterprise edition.


** This is currently just a place to take notes -- I do not yet have a functioning example **

Using the RDCOMServer package

One approach of many is to use the RDCOMServer package in R.

This section includes code that enables an Analytica model to call an R function; however, it requires the installation of an R-side package called RDCOMServer. I was unable to get this package installed, so I have not been able to verify that the code works. I am not an R user, so this might be something an R user would know how to do. If you know how to install the R package, please update the #Install packages section below.

Installation of R

  1. Install R
    1. After installer finished, launch R
    2. Type: Sys.setenv(R_LIBS_USER="C:/Users/«yourName»/AppData/Local/R/win-library/4.3")
      where you replace «yourName» with your login name.
    The setenv step is required because R installs into "C:\Program Files" by default, but then new packages can't be installed there, so this puts them into a writable location.

Install packages

This is the hard part.

  1. Install the RDCOMServer package for R
    1. Download the Windows Binary ZIP file
    2. Unzip it into %R_HOME%\library. For me this was "C:\Program Files\R\R-4.3.0\library"
  2. Install the SWinRegistry package.
    1. Download the Windows Binary ZIP file
    2. Unzip it into %R_HOME%\library. For me this was "C:\Program Files\R\R-4.3.0\library"
    3. In a CMD prompt:
      CD "C:\Program Files\R\R-4.3.0\bin\x64"
      Rcmd install RWinRegistry
  3. Install the R package Ruuid.
    1. Start R
    2. install.packages("BiocManager")
  4. Launch R
  5. Run:
    install.packages("devtools")
    devtools::install_github("omegahat/RDCOMServer")

-- I was unable to get R packages to install. As someone who doesn't use R, I'm afraid I don't know enough to get to first base to even get started. Aborted here. Sorry.

Server-side code

  • Note: This part is untested, since I haven't yet been able to successful install the required R packages.

Here's example R-code that creates a simple COM server with a single method named multiply:

library(RDCOMServer) 
 
serverDesc <- COMCreate("R.Server")
serverDesc$setClass("R.Server")
 
# Create the `multiply` method
serverDesc$addMethodDef(
  functionName = "multiply",
  args = c("x" = "numeric", "y" = "numeric"),
  return = "numeric",
  def = function(self, x, y) x * y
)
 
# Register the server
serverDesc$register()
 
# Start the server
COMServer()

Analytica-side call

  1. Create the variable:
    Variable RServer ::= COMCreateObject("R.Server")
    Note: Launch the R-side server before evaluating RServer
  2. Call the method within a different variable:
    Variable Y ::= RServer->multiply(5,7)
Comments


You are not allowed to post comments.