From J Wiki
Jump to: navigation, search

The DCOM interface allows R to be called from J using Windows COM.


1. Install R in the usual way, then install the R (D)COM package from CRAN dcom directory.

(An alternative may be to install from the R command line, using install.packages("rcom") - however, this has given errors when trying to load the server from J.)

2. Install the stats/r addon.

3. Load J, then:

   load 'stats/r/rdcom'
   '' conew 'prdcom'
   0 ". Rcmdr 'rnorm(1)'


Methods are defined in z with names beginning R, for example Rcmd. These in turn call verbs in the connection locale, named without the R, for example Rcmd calls cmd in the connection locale.

Only a few basic methods are defined. It should be easy to extend these as required. Each method sends its argument as a command to R.

The methods are:

Rcmd - send command, ignore any output
Rcmdr - send command, return only command output
Rcmdx - send command, return extended output


Example of setting values then calling an R routine using those values:

   Rcmd 'x = 1:5'
   Rcmd 'y = c(2,3,5,7,11)'
   Rcmdx 'lsfit(x,y)'
Intercept         X
     -1.0       2.2

[1]  0.8 -0.4 -0.6 -0.8  1.0

[1] TRUE

[1] -12.5219807   6.9570109  -0.9600727  -1.3426824   0.2747078

      Intercept          X
[1,] -2.2360680 -6.7082039
[2,]  0.4472136  3.1622777
[3,]  0.4472136 -0.1954395
[4,]  0.4472136 -0.5116673
[5,]  0.4472136 -0.8278950


Using Rcmdr in the following example gives an error, since the value has no COM representation. Instead use Rcmdx to retrieve the value.

   Rcmd 'x <- c(1,2,3,4)'
   Rcmd 'y <- c(2,3,5,7)'
   Rcmd 'z <- lm(y~x)'

   Rcmdr 'z'
Šdomain error: wd
Š   r=.r,LF,    wd'olemethod w base Evaluate *',>c

   Rcmdx 'z'
lm(formula = y ~ x)

(Intercept)            x
  1.110e-16    1.700e+00

This is equivalent to using a sink to get the value:

   Rcmd 'sink(file="c:/r.txt",append=TRUE,type="output")'
   Rcmd 'print(z)'
   Rcmd 'sink(file=NULL)'
   fread 'c:/r.txt'
lm(formula = y ~ x)

(Intercept)            x
  1.110e-16    1.700e+00

The next examples show and set the working directory:

   Rcmdr 'getwd()'
   Rcmd 'setwd ("c:/program files/r/r-2.2.0")'
   Rcmdr 'getwd()'
c:/program files/r/r-2.2.0

Example of function definition:

   Rcmd 'g <- function(x,y) {x + 2 * y}'
   Rcmdr 'typeof(g)'
   Rcmdr 'g(5,3)'

Similar example, but with LF-delimited text. In this case, box the command to avoid a cut on LF:

   Rcmd <'g <- function(x,y) {',LF,'a <- x',LF,'a + 2 * y}'
   Rcmdr 'g(10,20)'

Several commands may be given at once:

   Rcmdx 'a=c(2,3,5,7);b=a[1];c=10 + b;c;'
[1] 12

The R server can generate a plot:

   Rcmd 'plot(c(1,2,3,5,7,11),type="l")'

Source Code

The source code is in the public subversion respository, subdirectory r/dcom.