How to write a sum function in F# using RProvider?

2019-09-15 10:11发布

问题:

#r "RProvider.dll"
open RProvider
open RProvider.``base``

let add (x: float) (y: float) = 
    let sum = R.sum(x,y)
    sum.Value

VS gives me the error "The field, constructor or member 'Value' is not defined"

I also tried passing a vector to R.sum

from the little existing documentation (https://github.com/BlueMountainCapital/FSharpRProvider/wiki/How-To) I can't figure what to do

回答1:

The R.sum function seems to be a bit uglier to use, because it takes variable number of parameters and sums all of them (so the R type provider cannot infer what arguments it expects).

To get the result back, you'll need some extension methods:

open RDotNet 

There are two options for calling such function - you can just give it the arguments (without specifying their names), which works well enough for R.sum:

// You can pass parameters as an explicit array
R.sum([| 2.0; 3.0 |]).AsNumeric() |> Seq.head
// Or you can use the fact that the function takes 'params' array
R.sum(1.0, 2.0).AsNumeric() |> Seq.head

If you want to specify the name of the parameters (not really needed here, but useful for other function), then you can build a structure representing "named parameters" for an R function and call it:

let nums = namedParams ["x", 2.0; "y", 3.0]
R.sum(nums).AsNumeric() |> Seq.head

Note that the situation is nicer for functions where the parameters can be statically inferred. E.g.:

R.mean(x=[1;2;3])