.Net调用R语言

时间:2023-03-08 17:26:58
.Net调用R语言
 ///加载自己写的R语言算法库
public List<double> GetZTFB(double[] data)
{
List<double> par = new List<double>();
try
{
//调用R语言算法
REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance(null, true, null, null);
NumericVector x = engine.CreateNumericVector(data);
engine.SetSymbol("x", x);
string path = System.Windows.Forms.Application.StartupPath + "\\R_File\\ztfb.R";
path = "source(\"" + path + "\")";
path = path.Replace("\\", "\\\\");//这一步至关重要,否则会报错
engine.Evaluate(path);
engine.Evaluate("a<- ztfb(x)"); // engine.Evaluate(@"normal <- function(theta){
// mu <- theta[1]
// sigma <- theta[2]
// n <- length(x)
// logL <- -0.5*n*log(2*pi) - n*log(sigma) - sum(0.5*(x - mu)^2/sigma^2)
// return (-logL)
// }
// a<- nlminb(c(0,1),normal)");
NumericVector a = engine.Evaluate("a$par[1]").AsNumeric();
NumericVector b = engine.Evaluate("a$par[2]").AsNumeric();
par.Add(Convert.ToDouble(a[0]));
par.Add(Convert.ToDouble(b[0]));
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return par;
} ///加载R语言下载库
public List<double> GetZTFB(double[] data)
{
List<double> par = new List<double>();
try
{
//调用R语言算法
REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance(null, true, null, null);
///加载R语言库
engine.Evaluate("library(\"bit\", lib.loc=\"C:/Program Files/R/R-3.3.2/library\")")
NumericVector x = engine.CreateNumericVector(data);
engine.SetSymbol("x", x);
string path = System.Windows.Forms.Application.StartupPath + "\\R_File\\ztfb.R";
path = "source(\"" + path + "\")";
path = path.Replace("\\", "\\\\");//这一步至关重要,否则会报错
engine.Evaluate(path);
engine.Evaluate("a<- ztfb(x)"); // engine.Evaluate(@"normal <- function(theta){
// mu <- theta[1]
// sigma <- theta[2]
// n <- length(x)
// logL <- -0.5*n*log(2*pi) - n*log(sigma) - sum(0.5*(x - mu)^2/sigma^2)
// return (-logL)
// }
// a<- nlminb(c(0,1),normal)");
NumericVector a = engine.Evaluate("a$par[1]").AsNumeric();
NumericVector b = engine.Evaluate("a$par[2]").AsNumeric();
par.Add(Convert.ToDouble(a[0]));
par.Add(Convert.ToDouble(b[0]));
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return par;
}