///加載自己寫的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; }