Database Reference
In-Depth Information
Evaluating R iles from Clojure
We might not always want to feed R code from Clojure directly into R. Many times, we might
have iles containing R expressions and we would want to evaluate the whole ile.
We can do this quite easily too. Let's see how.
Getting ready
We must irst complete the recipe, Setting up R to talk to Clojure , and have Rserve running.
We must also have the Clojure-speciic parts of that recipe done and the connection to
Rserve made.
Moreover, we'll need access to the java.io.File class:
(import '[java.io File])
How to do it…
We'll irst deine a function to make evaluating a ile in R easier, and then we'll ind a ile
and execute it:
1. The function to evaluate a ile of R code takes a ilename and (optionally) a
connection to the R server. It feeds the ile to R using R's source function, and it
returns whatever R does:
(defn r-source
([filename] (r-source filename *r-cxn*))
([filename r-cxn]
(.eval r-cxn (str "source(\""
(.getAbsolutePath (File. filename))
"\")"))))
2.
For example, suppose we have a ile named chrsqr-example.R that creates a
random data table and performs a Χ² test on it:
dat <- data.frame(q1=sample(c("A","B","C"),
size=1000,replace=TRUE),
sex=sample(c("M","F"),
size=1000,replace=TRUE))
dtab <- with(dat,table(q1,sex))
(Xsq <- chisq.test(dtab))
 
Search WWH ::




Custom Search