首页 > 代码库 > .Net调用R语言
.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; }
.Net调用R语言
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。