# NOT RUN {
# Uncomment the next line to download and install Scala
# scalaInstall()
.rscalaJar()
scalaInfo(verbose=TRUE)
# }
# NOT RUN {
# Make an instance of the Scala interpreter and see how its output is captured.
s <- scala(serialize.output=TRUE)
capture.output(s %~% 'println("This is Scala "+scala.util.Properties.versionString)')
scalaSettings(s)
# Demonstrate convenient notation and string interpolation
stringFromScala <- s %~% '"Hello @{Sys.getenv("USER")} from @{R.Version()$nickname}" + "!"*10'
stringFromScala
# Set and get variables
s$rPi <- pi
s$rPi
s$val("rPi")
s$.val("rPi")
s$rPi <- I(pi) # Now rPi is an array of length one.
s$rPi # It doesn't matter to R...
s$.val("rPi") # ... but it does to Scala.
# Convenient notation
a1 <- s %~% "rPi(0)/2" # As an R value
a2 <- s %.~% "rPi(0)/2" # As a Scala reference
# References can be set
s$foo <- a2
s$foo
# Instantiate an object
seed <- 2349234L
rng <- s$.scala.util.Random$new(seed) # Scala equivalent: new scala.util.Random(seed)
# Call method of a reference
system.time(rng$nextInt(100L)) # Scala equivalent: rng.nextInt(100)
system.time(rng$nextInt(100L)) # Notice it runs much faster the second time due to caching
rInt <- rng$nextInt(100L,.EVALUATE=FALSE) # Define function to call quickly later without ...
rInt(100) # ... needing to protect scalars and ensure type.
# Call method of companion object and call methods of a reference
# Scala equivalent: (scala.math.BigInt("777",8) - 500).intValue
s$.scala.math.BigInt$apply("777",8L)$'-'(500L)$intValue()
# Example showing callback functionality
f <- function(func=NULL, data=numeric(), quiet=TRUE) s %!% '
if ( ! quiet ) println("Here I am in Scala.")
R.invokeD1(func, data.map(2*_), "verbose" -> !quiet ).sum
'
cube <- function(x, ignored.argument, verbose=TRUE) {
if ( verbose ) cat("Here I am in R.\n")
x^3
}
identical( f(cube,1:4,FALSE), sum((2*(1:4))^3) )
identical( f(cube,1:4,TRUE), sum((2*(1:4))^3) )
# Longer example showing more flexible than '%~%'
drawGaussian <- function(mean=0.0, sd=1.0, rng=scalaNull("scala.util.Random")) s %!% '
mean+sd*rng.nextDouble
'
drawGaussian(3,0.1,rng) # No scalar protection or casting is needed.
n.draws <- 100
s$random <- rng
system.time({
draws <- s %~% '
val result = new Array[Double](@{n.draws})
result(0) = random.nextGaussian
for ( i <- 1 until @{n.draws} ) {
result(i) = 0.5*result(i-1) + random.nextGaussian
}
result
'
acf(draws,plot=FALSE)
})
sampler <- function(nDraws=1L, rho=0.0, rng=scalaNull("scala.util.Random")) s %!% '
val result = new Array[Double](nDraws)
result(0) = rng.nextGaussian
for ( i <- 1 until nDraws ) {
result(i) = rho*result(i-1) + rng.nextGaussian
}
result
'
system.time(acf(sampler(n.draws,0.5,rng),plot=FALSE))
system.time(acf(sampler(n.draws,0.5,rng),plot=FALSE))
close(s)
# }
Run the code above in your browser using DataLab