如何从C#读取R脚本结果

时间:2016-09-08 02:24:02

标签: c# r r.net

我有一个关于如何为ODE模型拟合参数的R脚本。它适用于R.以下是我在R中的代码:

library(ggplot2) 
library(reshape2) 
library(deSolve) 
library(minpack.lm) 

#load concentration data
df=read.table("Test.txt")
names(df)=c("time","ca","cb","cc")

# prediction of concentration
# rate function
rxnrate=function(t,c,parms){

 k1=parms$k1
 k2=parms$k2

 r=rep(0,length(c))
 r[1]=-k1*c["A"]  #dcA/dt
 r[2]=k1*c["A"]-k2*c["B"]     

 return(list(r))

}

# function that calculates residual sum of squares
ssq=function(parms){

  # inital concentration 
    cinit=c(1,2)


  # time points for which conc is reported
  # include the points where data is available
  t=c(seq(0,5,0.1),df$time)
  t=sort(unique(t))

  # parms from the parameter estimation routine
  k1=parms[1]
  k2=parms[2]


  # solve ODE for a given set of parameters
  out=ode(y=cinit,times=t,func=rxnrate,parms=list(k1=k1,k2=k2))

  # Filter data that contains time points where data is available
  outdf=data.frame(out)
  outdf=outdf[outdf$time %in% df$time,]
  # Evaluate predicted vs experimental residual
  preddf=melt(outdf,id.var="time",variable.name="species",value.name="conc")
  expdf=melt(df,id.var="time",variable.name="species",value.name="conc")
  ssqres=preddf$conc-expdf$conc

  # return predicted vs experimental residual
  return(ssqres)
  }

# parameter fitting using levenberg marquart algorithm
# initial guess for parameters
  parms=c(k1=0.5,k2=0.5)

# fitting
fitval=nls.lm(par=parms,fn=ssq)

# Summary of fit
summary(fitval)

# Estimated parameter
parest=as.list(coef(fitval))

# mean error
ms=sqrt(deviance(fitval)/dof)
ms

当前阶段,我需要从C#访问结果(例如parest和ms)。我可以在R和C#之间生成连接。但是,我不知道如何使用C#代码来获取这些值。

static void Main(string[] args)
        {

            REngine.SetEnvironmentVariables(); 
            REngine engine = REngine.GetInstance();
            engine.Evaluate("source('myScript path')");

        }

在此之后,我需要使用什么来要求结果?

谢谢洪

1 个答案:

答案 0 :(得分:1)

您需要在C#代码中使用engine.getsymbol来访问R.script的结果。例如:

   var ResultsinC = engine.GetSymbol("R.list").AsNumeric().ToList();
   var X = engine.GetSymbol("R.matrix").AsNumericMatrix();

希望有所帮助。