Calling an R function in script

Sep 23, 2013 at 3:09 AM
Hi,

just started with RDOTNET - looks very promising. I'd like to call a function in an R script that takes arguments. Not sure how to do it. This is the latest attempt, but for one it doesn't like mixed string and numeric args:

CharacterVector A1 = engine.CreateCharacterVector(new string[] { "H" });
engine.SetSymbol("LU_COHORT_SPP_GROUP_CODE", A1);

NumericVector A2 = engine.CreateNumericVector(new double[] { 15.2 });
engine.SetSymbol("COHORT_MDH", A2);

NumericVector A3 = engine.CreateNumericVector(new double[] { 8.0 });
engine.SetSymbol("COHORT_AGE", A3);

var fSI = engine.GetSymbol("source(\"C:/Library/TimTest.R\")").AsFunction();
var SI = fSI.Invoke(new [] { A1, A2, A3} ).AsNumeric(); //Can't mix char and numeric args


Has anyone done anything like this?

Thanks - Tim
Developer
Oct 10, 2013 at 10:28 AM
The call engine.GetSymbol("source(\"C:/Library/TimTest.R\")").AsFunction(); is incorrect; GetSymbol is to get a symbol. A call to 'source' needs to be in a call to REngine.Evaluate. Depending on what your script contains, your sample code may or may not work once that is corrected;

All I can say is the following works as expected. I have just added it as a unit test actually.

Hope this helps
            engine.Evaluate("f <- function(a,b,c) {paste0(a,b,c)}");
            var f = engine.GetSymbol("f").AsFunction();
            CharacterVector a = engine.CreateCharacterVector(new string[] { "a" });
            NumericVector b = engine.CreateNumericVector(new double[] { 15.2 });
            NumericVector c = engine.CreateNumericVector(new double[] { 8.1 });
            var result = f.Invoke(new SymbolicExpression[] { a, b, c }).AsCharacter().ToArray();
            //Assert.AreEqual("a18.58.1", result[0]);
Oct 15, 2013 at 2:55 AM
Thank you, jperraud - it works perfectly!
            CharacterVector LU_COHORT_SPP_GROUP_CODE = engine.CreateCharacterVector(new string[] { "H" });
            NumericVector COHORT_MDH = engine.CreateNumericVector(new double[] { 15.2 });
            NumericVector COHORT_AGE = engine.CreateNumericVector(new double[] { 8.0 });

            var fSI = engine.Evaluate("SiteIndex").AsFunction();
            NumericVector result = fSI.Invoke(new SymbolicExpression[] { LU_COHORT_SPP_GROUP_CODE, COHORT_MDH, COHORT_AGE }).AsNumeric();
Oct 30, 2014 at 8:16 PM
Hi,

I'd like to get an answer to the original question - if I have a function defined in a file, how do I execute it from c#?

var f = engine.Evaluate("USE SCRIPT FROM FILE").AsFunction();

var result = f.Invoke().AsDataFrame();

I've tried OP's approach of using source(...) but that throws ' Value does not fall within the expected range.' error trying to evaluate.


Thank you,

Eugene
Oct 30, 2014 at 9:23 PM
Figured it out.
        engine.Evaluate(@"source('myfile')");
        var f = engine.GetSymbol("function_name").AsFunction();