Skip to content

Instantly share code, notes, and snippets.

@bitsnaps
Created July 26, 2022 15:44
Show Gist options
  • Save bitsnaps/8fcd383b9e4cb25617dba9cf4a30c211 to your computer and use it in GitHub Desktop.
Save bitsnaps/8fcd383b9e4cb25617dba9cf4a30c211 to your computer and use it in GitHub Desktop.
Groovy and Renjin the embedded R language engine
package demo
import javax.script.*
import org.renjin.script.*
class App {
static void main(String[] args){
// init values
int[] values = [1,2,3]
// Create a Renjin engine:
ScriptEngine engine = new RenjinScriptEngineFactory().scriptEngine
engine.eval("df <- data.frame(x=1:10, y=(1:10)+rnorm(n=10))")
engine.eval("print(df)")
engine.eval("print(lm(y ~ x, df))")
// Custom mean function
engine.put("input", values)
engine.eval('''
customMean <- function(vector) { mean(vector) }
''')
double mean = engine.eval("customMean(input)").asReal()
println("Mean: ${mean}")
}
}
plugins {
id 'groovy'
id 'application'
}
repositories {
mavenCentral()
maven { url "https://nexus.bedatadriven.com/content/groups/public" }
}
dependencies {
implementation 'org.codehaus.groovy:groovy-all:2.5.1'
implementation 'org.renjin:renjin-script-engine:3.5-beta76' // better output (still in beta)
//implementation 'org.renjin:renjin-script-engine:0.9.2723' // old but it works
testImplementation 'org.spockframework:spock-core:1.2-groovy-2.5'
testImplementation 'junit:junit:4.13.2'
}
application {
mainClassName = 'demo.App'
}
# Steps to reproduce
# Init a new app using gradle:
gradle init
# Create directory structure:
mkdir -p src/main/groovy/demo/
# Move App.groovy to that directory:
mv App.groovy src/main/groovy/demo/
# Run:
gradle run
# You should see something like this:
: '
x y
[1,] 1 1.909
[2,] 2 1.01
[3,] 3 3.587
[4,] 4 4.088
[5,] 5 5.857
[6,] 6 4.998
[7,] 7 5.634
[8,] 8 9.058
[9,] 9 8.701
[10,] 10 11.688
Call:
lm(formula = y ~ x, data = df)
Coefficients:
(Intercept) x
-0.113 1.048
Mean: 2.0
'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment