:ext QuasiQuotes
import qualified H.Prelude as H
H.initialize H.defaultConfig
-- print output
[rprint| lm(mpg ~ wt, data = mtcars) |]
Call: lm(formula = mpg ~ wt, data = mtcars) Coefficients: (Intercept) wt 37.285 -5.344
-- plot stuff
-- we just require ggplot2 as we do everything directly in R
[rgraph|
require(ggplot2)
ggplot(diamonds, aes(carat, price)) + geom_point() + theme(aspect.ratio = 1) |]
Assignment also works as usual:
[rprint| fact <- function(n) if(n == 0) 1 else n * fact(n - 1)
fact(10) |]
[1] 3628800
Call fact again...
[rprint| fact(10) |]
The embedded R interpreter is stateful, but for global assignment we need to use <<-
[r| fact <<- function(n) if(n == 0) 1 else n * fact(n - 1) |]
0x00007f86bf8df678
[rprint| fact(25) |]
[1] 1.551121e+25
The _hs suffix is used to splice values from Haskell into the R code:
-- a Haskell list
xs = [1..10] :: [Double]
xs
[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0]
[rprint| mean(xs_hs) |]
[1] 5.5
We can even use functions defined in Haskell in R:
import Data.Int
fact :: Int32 -> Int32
fact 0 = 1
fact n = n * fact (n - 1)
factR x = return $ fact x :: H.R s Int32
n = 6 :: Int32
[rprint| factR_hs(n_hs) |]
[1] 720
get_normals :: Double -> H.R s [Double]
get_normals n = do
H.dynSEXP <$> [r| rnorm(n_hs) |]
result <- H.runRegion $ get_normals 4
result
[1.1294181047596081,0.1277917949807154,-0.11111631846148341,1.878786090403989]
Now these are just normal Haskell values you can work with:
:t result