<jupyter_start><jupyter_text>Programming R from Haskell This notebook demonstrates integrating both R and Haskell in the same notebook, using `IHaskell-inline-r`.  Prelude First, a bit of setup. We need to enable quasiquotation, to embed R code into Haskell expressions:<jupyter_code>:ext QuasiQuotes<jupyter_output><empty_output><jupyter_text>Next, we need to make sure that R is initialized properly:<jupyter_code>import qualified H.Prelude as H
H.initialize H.defaultConfig<jupyter_output><empty_output><jupyter_text>R computations By default, computations in code cells are interpreted as Haskell code. For instance, here is a definition of the factorial function, in Haskell:<jupyter_code>fact 0 = 1
fact n = n * fact (n - 1)<jupyter_output><empty_output><jupyter_text>Here is a Haskell expression calling `fact`, together with its value:<jupyter_code>fact 10<jupyter_output><empty_output><jupyter_text>`inline-r` allows you to embed R expressions and R statements anywhere in Haskell code, using quasiquotation. The following is an IO action that asks R to print the value of the R code snipped embedded between the brackets:<jupyter_code>[rprint| 1 + 1 |]<jupyter_output><empty_output><jupyter_text>You can define the factorial function using R code, just as you can using Haskell code, so long as the R code is delineated within a quasiquote:<jupyter_code>[r| fact <<- function(n) if(n == 0) 1 else n * fact(n - 1) |]<jupyter_output><empty_output><jupyter_text>The `r` quasiquote is used for embedding R code that is only useful for its side effects. This is the case with the code above which has the side effect of binding `fact` in the toplevel environment. Applying the definition:<jupyter_code>[rprint| fact(10) |]<jupyter_output><empty_output><jupyter_text>R graphics R has extremely powerful plotting facilities. They are available out-of-the-box:<jupyter_code>[rgraph| plot(cars) |]<jupyter_output><empty_output><jupyter_text>For effect, we can fit a straight line through our data set:<jupyter_code>[rgraph| plot(cars); abline(lm(cars$dist ~ cars$speed), col="red") |]<jupyter_output><empty_output><jupyter_text>R code snippets that have graphical output should be embedded using the `rgraph` quasiquote. The other quasiquotes ignore graphical output. For a more complex example, consider the following density plot (requires `ggplot2` to be installed):<jupyter_code>[r| require("ggplot2") |]
[rgraph|
  Xv <- c(rnorm (500, 10,3), rnorm (500, 50, 20), rnorm (500, 70, 20))
  Yv <- c(rnorm (500, 10,3), rnorm (500, 70, 5), rnorm (500, 30, 5))
  myd <- data.frame(Xv, Yv)

  ggplot(myd, aes(x = Xv, y = Yv)) + geom_point() + geom_density2d() + theme_bw() |]<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup