Interfaces/R/Jserver4R/Examples

From J Wiki
< Interfaces‎ | R
Jump to navigation Jump to search
Overview | Methods | Examples | Quirks

R cover functions

The script ~addons/stats/jserver4r/jserver.R defines typical cover functions for calling J:

Jinit(loadprofile=TRUE) initialize J, with optional profile
Jdo("exp") execute J expression, returning result code
Jexec("exp") execute J expression and return result
Jget("name") get value of J noun
Jgetr() get last J output
Jset("name",value) set J name to R value, returning result code
Jrun() run a J REPL, until .... is entered.

Any result code is either 0=OK or the error code from the J engine call.

Example session

The examples assume that the jserver.R script is in your R working directory and has been updated for your setup. Start R, then:

> source("jserver.R")          # load R cover functions

> Jinit()                      # initialize J
[1] 0

> Jset("pies",pi*0:3)          # set a J noun and get it
[1] 0
> Jget("pies")
[1] 0.000000 3.141593 6.283185 9.424778

> Jset("b",c(TRUE,FALSE,NA,TRUE))  # R booleans are J 0 1 and 2=NA
[1] 0
> Jget("b")
[1] 1 0 2 1

> Jset("n",c(2,NA,5))          # integer or float NA is set to __ (-Inf)
[1] 0
> Jget("n")
[1]    2 -Inf    5

> (m=matrix(0:5,2,3))          # R arrays are in column-matrix order
     [,1] [,2] [,3]
[1,]    0    2    4
[2,]    1    3    5
> Jset("mat",m)
[1] 0
> identical(m,Jget("mat"))     # J returns the matrix as defined in R
[1] TRUE

> Jdo("mat")                   # J stores the matrix in row order
[1] 0
> cat(Jgetr())
0 1 2
3 4 5

> Jexec("+/mat")               # confirms the matrix is in row order
[1] 3 5 7

R Character Vectors and J Boxed Lists

An R character vector is a list of strings, and corresponds to a J boxed list of strings. This is because in R, a string is a single thing, not a list of the characters making up the string. For example:

> (v=c("hello","world"))       # R character vector
[1] "hello" "world"
> Jset("vec",v)
[1] 0
> identical(v,Jget("vec"))     # J returns the same character vector
[1] TRUE

> Jdo("vec")                   # J stores the character vector as a boxed list
[1] 0
> cat(Jgetr())
┌─────┬─────┐
│hello│world│
└─────┴─────┘

A J boxed list that is all character strings is returned as an R character vector, otherwise it is returned as an R list:

> Jexec("2.1;'hello';i.3")     # a J boxed list that is not all strings
[[1]]
[1] 2.1

[[2]]
[1] "hello"

[[3]]
[1] 0 1 2

Interactive REPL

> Jrun()                       # start a REPL

   b                           # b previously defined
1 0 2 1

   n                           # n previously defined
2 __ 5 

   mat                         # mat previously defined
0 1 2
3 4 5

   A=: p:i.5                   # define A

   ....                        # exit the REPL

> Jget("A")                    # read value set in REPL
[1]  2  3  5  7 11