I am following some R examples from a book on stochastic simulation, and being familiar with F# and not familiar with R -I decided to try out the R type provider.
Today I come across a code snippet which I cannot figure out how to execute through the R type provider.
> Nit = c(0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,6,6,6)
> AOB = c(4.26,4.15,4.68,6.08,5.87,6.92,6.87,6.25,6.84,6.34,6.56,6.52,7.39,7.38,7.74,7.76,8.14,7.22)
> AOBm=tapply(AOB,Nit,mean) #means of AOB
> Nitm=tapply(Nit,Nit,mean) #means of Nit
> fitAOB=lm(AOBm∼ns(Nitm,df=2)) #natural spline
The corresponding F# code could look like following:
open System
open System.Linq
open RDotNet
open RProvider
open RProvider.``base``
open RProvider.stats
open RProvider.graphics
open RProvider.splines
let mean (l: float seq) = Seq.sum l / float(Seq.length l)
let Nit = [0;0;0;1;1;1;2;2;2;3;3;3;4;4;4;6;6;6]
let AOB = [4.26;4.15;4.68;6.08;5.87;6.92;6.87;6.25;6.84;6.34;6.56;6.52;7.39;7.38;7.74;7.76;8.14;7.22]
let AOBm =
query {
for x in List.zip AOB Nit do
groupBy (snd x) into g
select (g |> Seq.map fst |> mean) }
|> List.ofSeq
namedParams [
"AOBm", AOBm :> obj
"Nitm", Nit.Distinct() :> obj
]
|> R.data_frame
|> fun data -> R.lm(formula="AOBm~ns(Nitm,df=2)", data=data)
However, when I try to execute the last lines to fit the linear model, I get the exception:
RDotNet.EvaluationException: Error in eval(expr, envir, enclos) : could not find function "ns"
So I guess that I either have to pass in
R.ns(Nit.Distinct(),df=2)
into my named parameters... Or that I somehow should be able to load the 'splines::ns' function into the current environment.. Or that I somehow can compose the formula using R.formula(...).. However, all my attempts to do these things has failed so far..
so how can I call a function from a library in the formula when fitting a linear model using R type provider?
You need to either
add
library(splines)
to your R code, ormake the call fully qualified:
splines::ns(...)
but because
ns()
is used inside aFormula
object, the first approach is preferable.