//Method to create DataFrame public void createDF() { PISetup ps = new PISetup(); Dictionary <DateTime, Object> dict = ps.getArchiveValues(); Double[] db = new double[dict.Count]; String[] dt = new String[dict.Count]; int i = 0; foreach (object ob in dict.Values) { db[i] = Convert.ToDouble(ob); i += 1; } int j = 0; foreach (DateTime da in dict.Keys) { dt[j] = Convert.ToString(da); j += 1; } NumericVector myNum = engine.CreateNumericVector(db); CharacterVector myCha = engine.CreateCharacterVector(dt); engine.SetSymbol("Time", myCha); engine.SetSymbol("BA.TEMP.1", myNum); engine.Evaluate("df <- data.frame(Timestamp=c(Time), BA.TEMP.1=c(BA.TEMP.1))"); //engine.Evaluate("write.csv(df, file = \"C:/File_1.csv\")"); //engine.Evaluate("View(df)"); }
private void DrawChart(string chartName, IEnumerable <IEnumerable <Tuple <double, double> > > data, double lowX, double highX, double lowY, double highY) { if (data.Count() == 0) { return; } var colorIndex = 0; var colors = new[] { "red", "green", "blue", "yellow" }; this.engine.Evaluate("dev.new()"); this.engine.SetSymbol("lowX", this.engine.CreateNumeric(lowX)); //this.engine.SetSymbol("main", this.engine.CreateCharacter("Chart number1")); this.engine.SetSymbol("highX", this.engine.CreateNumeric(highX)); this.engine.SetSymbol("lowY", this.engine.CreateNumeric(lowY)); this.engine.SetSymbol("highY", this.engine.CreateNumeric(highY)); this.engine.Evaluate($"plot(1, type=\"n\", xlab=\"X\", ylab=\"Y\", xlim=c(lowX, highX), ylim=c(lowY, highY), main='{chartName}')"); foreach (var val in data) { // get xs engine.SetSymbol("x", engine.CreateNumericVector(val.Select(e => e.Item1))); // get ys engine.SetSymbol("y", engine.CreateNumericVector(val.Select(e => e.Item2))); engine.SetSymbol("color", engine.CreateCharacterVector(new[] { colors[colorIndex % colors.Length] })); engine.Evaluate("points(x, y, col = color)"); colorIndex++; } }
private void SetupDotNetToRConverters() { SetupDotNetToRConverter(typeof(void), p => null); SetupDotNetToRConverter(typeof(string), p => engine.CreateCharacter((string)p)); SetupDotNetToRConverter(typeof(string[]), p => engine.CreateCharacterVector((string[])p)); SetupDotNetToRConverter(typeof(List <string>), p => engine.CreateCharacterVector((IEnumerable <string>)p)); SetupDotNetToRConverter(typeof(IList <string>), p => engine.CreateCharacterVector((IEnumerable <string>)p)); SetupDotNetToRConverter(typeof(ICollection <string>), p => engine.CreateCharacterVector((IEnumerable <string>)p)); SetupDotNetToRConverter(typeof(IEnumerable <string>), p => engine.CreateCharacterVector((IEnumerable <string>)p)); SetupDotNetToRConverter(typeof(string[, ]), p => engine.CreateCharacterMatrix((string[, ])p)); SetupDotNetToRConverter(typeof(int), p => engine.CreateInteger((int)p)); SetupDotNetToRConverter(typeof(int[]), p => engine.CreateIntegerVector((int[])p)); SetupDotNetToRConverter(typeof(List <int>), p => engine.CreateIntegerVector((IEnumerable <int>)p)); SetupDotNetToRConverter(typeof(IList <int>), p => engine.CreateIntegerVector((IEnumerable <int>)p)); SetupDotNetToRConverter(typeof(ICollection <int>), p => engine.CreateIntegerVector((IEnumerable <int>)p)); SetupDotNetToRConverter(typeof(IEnumerable <int>), p => engine.CreateIntegerVector((IEnumerable <int>)p)); SetupDotNetToRConverter(typeof(int[, ]), p => engine.CreateIntegerMatrix((int[, ])p)); SetupDotNetToRConverter(typeof(bool), p => engine.CreateLogical((bool)p)); SetupDotNetToRConverter(typeof(bool[]), p => engine.CreateLogicalVector((bool[])p)); SetupDotNetToRConverter(typeof(List <bool>), p => engine.CreateLogicalVector((IEnumerable <bool>)p)); SetupDotNetToRConverter(typeof(IList <bool>), p => engine.CreateLogicalVector((IEnumerable <bool>)p)); SetupDotNetToRConverter(typeof(ICollection <bool>), p => engine.CreateLogicalVector((IEnumerable <bool>)p)); SetupDotNetToRConverter(typeof(IEnumerable <bool>), p => engine.CreateLogicalVector((IEnumerable <bool>)p)); SetupDotNetToRConverter(typeof(bool[, ]), p => engine.CreateLogicalMatrix((bool[, ])p)); SetupDotNetToRConverter(typeof(double), p => engine.CreateNumeric((double)p)); SetupDotNetToRConverter(typeof(double[]), p => engine.CreateNumericVector((double[])p)); SetupDotNetToRConverter(typeof(List <double>), p => engine.CreateNumericVector((IEnumerable <double>)p)); SetupDotNetToRConverter(typeof(IList <double>), p => engine.CreateNumericVector((IEnumerable <double>)p)); SetupDotNetToRConverter(typeof(ICollection <double>), p => engine.CreateNumericVector((IEnumerable <double>)p)); SetupDotNetToRConverter(typeof(IEnumerable <double>), p => engine.CreateNumericVector((IEnumerable <double>)p)); SetupDotNetToRConverter(typeof(double[, ]), p => engine.CreateNumericMatrix((double[, ])p)); SetupDotNetToRConverter(typeof(DateTime), p => engine.CreatePosixct((DateTime)p)); SetupDotNetToRConverter(typeof(DateTime[]), p => engine.CreatePosixctVector((DateTime[])p)); SetupDotNetToRConverter(typeof(List <DateTime>), p => engine.CreatePosixctVector((IEnumerable <DateTime>)p)); SetupDotNetToRConverter(typeof(IList <DateTime>), p => engine.CreatePosixctVector((IEnumerable <DateTime>)p)); SetupDotNetToRConverter(typeof(ICollection <DateTime>), p => engine.CreatePosixctVector((IEnumerable <DateTime>)p)); SetupDotNetToRConverter(typeof(IEnumerable <DateTime>), p => engine.CreatePosixctVector((IEnumerable <DateTime>)p)); SetupDotNetToRConverter(typeof(DateTime[, ]), p => engine.CreatePosixctMatrix((DateTime[, ])p)); SetupDotNetToRConverter(typeof(TimeSpan), p => engine.CreateDiffTime((TimeSpan)p)); SetupDotNetToRConverter(typeof(TimeSpan[]), p => engine.CreateDiffTimeVector((TimeSpan[])p)); SetupDotNetToRConverter(typeof(List <TimeSpan>), p => engine.CreateDiffTimeVector((IEnumerable <TimeSpan>)p)); SetupDotNetToRConverter(typeof(IList <TimeSpan>), p => engine.CreateDiffTimeVector((IEnumerable <TimeSpan>)p)); SetupDotNetToRConverter(typeof(ICollection <TimeSpan>), p => engine.CreateDiffTimeVector((IEnumerable <TimeSpan>)p)); SetupDotNetToRConverter(typeof(IEnumerable <TimeSpan>), p => engine.CreateDiffTimeVector((IEnumerable <TimeSpan>)p)); SetupDotNetToRConverter(typeof(TimeSpan[, ]), p => engine.CreateDiffTimeMatrix((TimeSpan[, ])p)); }
private void TransferDataToR() { for (int i = 1; i <= piValuesList.Count; i++) { double[] values = ConvertValuesToDoubleArray(piValuesList[i - 1]); double[] ts = ConvertTSToDoubleArray(piValuesList[i - 1]); NumericVector tagval = engine.CreateNumericVector(values); engine.SetSymbol("tag" + i.ToString() + "val", tagval); NumericVector tag_tsd = engine.CreateNumericVector(ts); engine.SetSymbol("tag" + i.ToString() + "tsd", tag_tsd); engine.Evaluate("tag" + i.ToString() + "ts<-as.POSIXct(tag" + i.ToString() + "tsd, origin='1970-01-01')"); engine.Evaluate("tag" + i.ToString() + "<- data.frame(tag" + i.ToString() + "ts,tag" + i.ToString() + "val)"); } }
static void Main(string[] args) { REngine.SetEnvironmentVariables(); REngine engine = REngine.GetInstance(); // REngine requires explicit initialization. // You can set some parameters. engine.Initialize(); // .NET Framework array to R vector. NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 }); engine.SetSymbol("group1", group1); // Direct parsing from R script. NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric(); // Test difference of mean and get the P-value. GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList(); double p = testResult["p.value"].AsNumeric().First(); Console.WriteLine("Group1: [{0}]", string.Join(", ", group1)); Console.WriteLine("Group2: [{0}]", string.Join(", ", group2)); Console.WriteLine("P-value = {0:0.000}", p); // you should always dispose of the REngine properly. // After disposing of the engine, you cannot reinitialize nor reuse it engine.Dispose(); }
public void ConstruirMejorModeloArmonico(ref REngine motorDeR, string nombreDelVectorDeDatosR, NumericVector datosParaR, double[] vectorDeDatos, out double[] vectorValoresDelModelo, int usarDatosDesde, int usarDatosHasta, out double declinacionInicial, ref double produccionInicial, ref double r2, ref double aic) { int numeroDeParametros = 2; double declinacionInicialLocal; double produccionInicialLocal; double[] vectorLocalValoresDelModelo = new double[usarDatosHasta - usarDatosDesde + 1]; NumericVector coeficientesDesdeR = motorDeR.CreateNumericVector(2); int numeroDeDatos = usarDatosHasta - usarDatosDesde + 1; motorDeR.Evaluate("matriz <- matrix(nrow = length(" + nombreDelVectorDeDatosR + "), ncol = 2)"); motorDeR.Evaluate("tiempo <- c(1:(length(" + nombreDelVectorDeDatosR + ")))"); motorDeR.Evaluate("matriz[,1] <- 1"); motorDeR.Evaluate("matriz[,2] <- tiempo"); motorDeR.Evaluate("vectorInverso <- 1/(" + nombreDelVectorDeDatosR + ")"); motorDeR.Evaluate("i=1\nwhile (i < length(vectorInverso))\n{\nif (" + nombreDelVectorDeDatosR + "[i] == 0)\n{\nvectorInverso[i] = 0\n}\ni = i + 1\n}"); motorDeR.Evaluate("coeficientesArmonico <- solve(t(matriz) %*% matriz) %*% (t(matriz) %*% vectorInverso)"); coeficientesDesdeR = motorDeR.Evaluate("coeficientesArmonico").AsNumeric(); produccionInicialLocal = 1 / (coeficientesDesdeR[0]); declinacionInicialLocal = coeficientesDesdeR[1] / coeficientesDesdeR[0]; DarValoresAlModeloArmonico(ref vectorLocalValoresDelModelo, produccionInicialLocal, declinacionInicialLocal); HallarR2(vectorDeDatos, vectorLocalValoresDelModelo, usarDatosDesde, usarDatosHasta, out r2); HallarAIC(vectorDeDatos, vectorLocalValoresDelModelo, usarDatosDesde, usarDatosHasta, out aic, numeroDeParametros); vectorValoresDelModelo = vectorLocalValoresDelModelo; produccionInicial = produccionInicialLocal; declinacionInicial = declinacionInicialLocal; }
public static void barchart_months_revenue(this REngine engine) { //# Create the data for the chart. // H < -c(7, 12, 28, 3, 41) //M < -c("一月", "二月", "三月", "四月", "五月") //# Give the chart file a name. //png(file = "barchart_months_revenue.png") //# Plot the bar chart. //barplot(H, names.arg = M, xlab = "月份", ylab = "收入量", col = "blue", //main = "收入图表", border = "red") //# Save the file. //dev.off() var numVer = engine.CreateNumericVector(new double[] { 110, 300, 390, 200 }); var charVer = engine.CreateCharacterVector(new string[] { "一月", "二月", "三用", "四月" }); var mainChar = engine.CreateCharacter("收入图表"); engine.SetSymbol("H", numVer); engine.SetSymbol("M", charVer); engine.SetSymbol("name", mainChar); engine.Evaluate("png(file = 'barchart_months_revenue.jpg')"); engine.Evaluate("barplot(H,names.arg=M,xlab='月份',ylab='收入量',col='blue',main=name,border='red')"); engine.Evaluate("dev.off()"); }
/// <summary> /// /// </summary> /// <param name="engine"></param> public static void Age_title_colours(this REngine engine) { //# Create data for the graph. // x < -c(11, 30, 39, 20) //labels < -c("70后", "80后", "90后", "00后") //# Give the chart file a name. //png(file = "age_title_colours.jpg") //# Plot the chart with title and rainbow color pallet. //pie(x, labels, main = "出生年龄段 - 饼状图", col = rainbow(length(x))) //# Save the file. //dev.off() var numVer = engine.CreateNumericVector(new double[] { 11, 30, 39, 20 }); var charVer = engine.CreateCharacterVector(new string[] { "70后", "80后", "90后", "00后" }); var mainChar = engine.CreateCharacter("出生年龄段 - 饼状图"); engine.SetSymbol("x", numVer); engine.SetSymbol("labels", charVer); engine.SetSymbol("main", mainChar); var length = engine.Evaluate("rainbow(length(x))"); engine.SetSymbol("col", length); engine.Evaluate("png(file = 'age_title_colours.jpg')"); engine.Evaluate("pie(x,labels,main=main,col = col)"); engine.Evaluate("dev.off()"); }
static void Main(string[] args) { REngine.SetEnvironmentVariables(@"c:\Program Files\Microsoft\R Client\R_SERVER\bin\x64\", @"c:\Program Files\Microsoft\R Client\R_SERVER\"); // <-- May be omitted; the next line would call it. REngine engine = REngine.GetInstance(); // A somewhat contrived but customary Hello World: //CharacterVector charVec = engine.CreateCharacterVector(new[] { "Hello, R world!, .NET speaking" }); //engine.SetSymbol("greetings", charVec); //engine.Evaluate("str(greetings)"); // print out in the console //string[] a = engine.Evaluate("'Hi there .NET, from the R engine'").AsCharacter().ToArray(); //Console.WriteLine("R answered: '{0}'", a[0]); //Console.WriteLine("Press any key to exit the program"); //Console.ReadKey(); // .NET Framework array to R vector. NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 }); engine.SetSymbol("group1", group1); // Direct parsing from R script. NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric(); // Test difference of mean and get the P-value. GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList(); double p = testResult["p.value"].AsNumeric().First(); Console.WriteLine("Group1: [{0}]", string.Join(", ", group1)); Console.WriteLine("Group2: [{0}]", string.Join(", ", group2)); Console.WriteLine("P-value = {0:0.000}", p); Console.ReadKey(); engine.Dispose(); }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { SetStartDate(2013, 10, 07); //Set Start Date SetEndDate(2013, 10, 11); //Set End Date SetCash(100000); //Set Strategy Cash // Find more symbols here: http://quantconnect.com/data AddEquity("SPY", Resolution.Second); REngine engine = REngine.GetInstance(); engine.Evaluate("print('This is from R command.')"); // .NET Framework array to R vector. NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 }); engine.SetSymbol("group1", group1); // Direct parsing from R script. NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric(); // Test difference of mean and get the P-value. GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList(); double p = testResult["p.value"].AsNumeric().First(); // you should always dispose of the REngine properly. // After disposing of the engine, you cannot reinitialize nor reuse it engine.Dispose(); }
private static double GetRecomendedQuntity(List <double> countList) { List <double> data = new List <double>(); for (int i = 0; i < countList.Count; i++) { data.Add(countList[i]); } REngine.SetEnvironmentVariables(); REngine engine = REngine.GetInstance(); engine.Initialize(); NumericVector dataVector = engine.CreateNumericVector(data.ToArray()); engine.SetSymbol("dataVector", dataVector); engine.Evaluate("graphObj <- ts(dataVector, frequency=1, start=c(1, 1, 1))"); engine.Evaluate("library(\"forecast\")"); engine.Evaluate("arimaFit <- arima(graphObj,order=c(2,2,2))"); engine.Evaluate("fcast <- forecast(arimaFit, h=1)"); engine.Evaluate("result <- as.numeric(fcast$mean)"); NumericVector forecastResult = engine.GetSymbol("result").AsNumeric(); double result = forecastResult.First(); engine.Dispose(); return(result); }
public static void TestMethod() { REngine.SetEnvironmentVariables(); // There are several options to initialize the engine, but by default the following suffice: REngine engine = REngine.GetInstance(); // .NET Framework array to R vector. NumericVector testTs = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 }); engine.SetSymbol("testTs", testTs); // Direct parsing from R script. //NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric(); //auto arima for monthly engine.Evaluate("tsValue <- ts(testTs, frequency=1, start=c(2010, 1, 1))"); engine.Evaluate("library(forecast)"); engine.Evaluate("arimaFit <- auto.arima(tsValue)"); engine.Evaluate("fcast <- forecast(tsValue, h=5)"); var a = engine.Evaluate("fcast <- forecast(tsValue, h=5)").AsCharacter(); NumericVector forecasts = engine.Evaluate("fcast$mean").AsNumeric(); foreach (var item in forecasts) { Console.WriteLine(item); } engine.Dispose(); }
public void OnData(TradeBars data) { if (IsWarmingUp) { return; } var logData = _window.Select(closingPrice => Math.Log10(closingPrice)); var diff = logData.Zip(logData.Skip(1), (x, y) => y - x); var returns = _engine.CreateNumericVector(diff); _engine.SetSymbol("roll.returns", returns); _engine.Evaluate(@"source('C:\Users\M\Documents\Visual Studio 2015\Projects\Trading\Trading\arima_garch.r')"); var direction = _engine.GetSymbol("directions").AsInteger()[0]; var holdings = Portfolio[Symbol].Quantity; if (holdings <= 0 && direction == 1) { Log("BUY >> " + Securities[Symbol].Price); SetHoldings(Symbol, 1.0); } else if (holdings >= 0 && direction == -1) { Log("SELL >> " + Securities[Symbol].Price); SetHoldings(Symbol, -1.0); } }
public static SymbolicExpression CreateDiffTimeVector(this REngine engine, IEnumerable <TimeSpan> data) { var numeric = data.ToArray().FromTimeSpan(); var sexp = engine.CreateNumericVector(numeric); return(sexp.AddDiffTimeAttributes()); }
// // GET: /Home/ public ActionResult Index() { REngine.SetEnvironmentVariables(); REngine engine = REngine.GetInstance(); engine.Initialize(); NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 }); engine.SetSymbol("group1", group1); // Direct parsing from R script. NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric(); // Test difference of mean and get the P-value. GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList(); double p = testResult["p.value"].AsNumeric().First(); Console.WriteLine("Group1: [{0}]", string.Join(", ", group1)); Console.WriteLine("Group2: [{0}]", string.Join(", ", group2)); Console.WriteLine("P-value = {0:0.000}", p); // you should always dispose of the REngine properly. // After disposing of the engine, you cannot reinitialize nor reuse it engine.Dispose(); return(View()); }
static void Main(string[] args) { // Set the folder in which R.dll locates. var envPath = Environment.GetEnvironmentVariable("PATH"); var rBinPath = @"C:\Program Files (x86)\R\R-2.11.1\bin"; //var rBinPath = @"C:\Program Files\R\R-2.11.1-x64\bin"; // Doesn't work ("DLL was not found.") Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + rBinPath); using (REngine engine = REngine.CreateInstance("RDotNet")) { // Initializes settings. engine.Initialize(); // .NET Framework array to R vector. NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 }); engine.SetSymbol("group1", group1); // Direct parsing from R script. NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric(); // Test difference of mean and get the P-value. GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList(); double p = testResult["p.value"].AsNumeric().First(); Console.WriteLine("Group1: [{0}]", string.Join(", ", group1)); Console.WriteLine("Group2: [{0}]", string.Join(", ", group2)); Console.WriteLine("P-value = {0:0.000}", p); } }
static void RMain(string[] args) { REngine.SetEnvironmentVariables(); // There are several options to initialize the engine, but by default the following suffice: using (REngine engine = REngine.GetInstance()) { // .NET Framework array to R vector. NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 }); engine.SetSymbol("group1", group1); // Direct parsing from R script. NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric(); // Test difference of mean and get the P-value. GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList(); double p = testResult["p.value"].AsNumeric().First(); Console.WriteLine("Group1: [{0}]", string.Join(", ", group1)); Console.WriteLine("Group2: [{0}]", string.Join(", ", group2)); Console.WriteLine("P-value = {0:0.000}", p); // you should always dispose of the REngine properly. // After disposing of the engine, you cannot reinitialize nor reuse it // engine.Dispose(); } // End Using engine } // End Sub RMain
// C:\Program Files\R\R-3.2.4revised public double[] ForeCast(double[] serie, int numberOfPredictions) { // source: http://stackoverflow.com/questions/14879697/retrieve-results-from-r-evaluation-using-r-net engine.Initialize(); // code below to run the first time, choose yes to install in personal directory // engine.Evaluate("install.packages(\"forecast\")"); NumericVector testGroup = engine.CreateNumericVector(serie); engine.SetSymbol("testGroup", testGroup); engine.Evaluate("testTs <- c(testGroup)"); NumericVector ts = engine.GetSymbol("testTs").AsNumeric(); engine.Evaluate("tsValue <- ts(testTs, frequency=1, start=c(2016, 4, 9))"); engine.Evaluate("library(forecast)"); engine.Evaluate("arimaFit <- auto.arima(tsValue)"); engine.Evaluate("fcast <- forecast(tsValue, h=" + numberOfPredictions + ")"); engine.Evaluate("results <- fcast$mean"); //engine.Evaluate("plot(fcast)"); var fcast = engine.GetSymbol("results").AsNumeric().Select(d => Math.Round(d, 2)).ToArray(); //var nv = ts.AsNumeric().ToArray().Select(a => ""+ a).Aggregate((a,b) => a + "," + b); //var rstring = fcast.Select(a => "" + a).Aggregate((a, b) => a + "," + b); ////var result = nv.ToArray<double>(); return(fcast); }
private void button1_Click(object sender, EventArgs e) { engine.Evaluate("library('ks')"); engine.Evaluate("library(ggplot2)"); //engine.Evaluate("library(sm)"); for (int i = 0; i < values.Length; i++) { Random r = new Random(3); //r.NextDouble(); values[i] += 1000 * r.NextDouble(); } data = engine.CreateNumericVector(values); engine.SetSymbol("group1", data); engine.Evaluate("fhat <- kde(group1, h = hpi(group1))"); engine.Evaluate("X <- rkde(fhat = fhat, n = length(group1))"); //engine.Evaluate("p1 <- plot(density(group1))"); // engine.Evaluate("p2 <- plot(density(X))"); string TempImagePath = @"C:\Users\Tom\Desktop\test.png"; engine.Evaluate(string.Format("png('{0}', {1}, {2})", TempImagePath.Replace('\\', '/'), pictureBox1.Width, this.pictureBox1.Height)); engine.Evaluate("par(mfrow=c(1,2))"); engine.Evaluate("plot(density(group1))"); engine.Evaluate("plot(density(X))"); engine.Evaluate("dev.off()"); this.pictureBox1.ImageLocation = TempImagePath; //engine.Evaluate("hist(group1)"); //engine.Evaluate("d <- density(group1)"); //engine.Evaluate("sm.density(group1, PANEL =\"TRUE\")"); }
public static SymbolicExpression CreatePosixctVector(this REngine engine, DateTime[] data) { var numeric = data.ToTicks(out var tzone); var sexp = engine.CreateNumericVector(numeric); return(sexp.AddPosixctAttributes(tzone)); }
static void TestOptimCsharp(REngine engine) { var rand = new Random(0); int n = 10000; double x, y, r, xb, yb, rb; rb = double.MaxValue; xb = yb = double.MaxValue; engine.Evaluate("rosen <- function(x, y) { (1-x)**2 + 100*(y-x*x)**2 }"); Console.WriteLine("*** Try a basic way to call the function in R ***"); for (int i = 0; i < n; i++) { x = -1 + rand.NextDouble() * (3 - (-1)); y = -1 + rand.NextDouble() * (3 - (-1)); r = engine.Evaluate(string.Format("rosen({0}, {1})", x, y)).AsNumeric().ToArray()[0]; if (r < rb) { rb = r; xb = x; yb = y; } } Console.WriteLine("The best score r={0} is for x={1}, y={2}", rb, xb, yb); Console.WriteLine("*** Try an R function 'pointer' with a vectorized function call. Faster, if you can do it this way***"); var f = engine.GetSymbol("rosen").AsFunction(); double[] xa = new double[n], ya = new double[n]; rand = new Random(0); for (int i = 0; i < n; i++) { xa[i] = -1 + rand.NextDouble() * (3 - (-1)); ya[i] = -1 + rand.NextDouble() * (3 - (-1)); } double[] ra = f.Invoke(new[] { engine.CreateNumericVector(xa), engine.CreateNumericVector(ya) }) .AsNumeric().ToArray(); rb = ra.Min(); int indBest = -1; for (int i = 0; i < ra.Length; i++) { // no which.min in C#. Should call R here too... if (ra[i] <= rb) { indBest = i; } } Console.WriteLine("The best score r={0} is for x={1}, y={2}", rb, xa[indBest], ya[indBest]); }
static double calcSDev(REngine engine, double[] arr) { // Note: only one quick and slightly dirty way to do it NumericVector rVector = engine.CreateNumericVector(arr); engine.SetSymbol("x", rVector); return(engine.Evaluate("sd(x)").AsNumeric() [0]); }
// STATUS: this works /// <summary> Get a single pitcher's winning percentage </summary> /// <remarks> Calculating Baseball Data with R </remarks> public void CalculatePitcherWinningPercentage() { REngine engine = CreateNewREngine(); // PITCHER WINS --> each number represents number of wins for a single season NumericVector pitcherWins = engine.CreateNumericVector(new double[] { 8, 21, 15, 21, 21, 22, 14 }); engine.SetSymbol("pitcherWins", pitcherWins); // PITCHER LOSSES --> each number represents number of losses for a single season NumericVector pitcherLosses = engine.CreateNumericVector(new double[] { 5, 10, 12, 14, 17, 14, 19 }); engine.SetSymbol("pitcherLosses", pitcherLosses); // WINNING PERCENTAGE --> calculate the winning percentage for each single season NumericVector winningPercentage = engine.Evaluate("winningPercentage <- 100 * pitcherWins / (pitcherWins + pitcherLosses)").AsNumeric(); }
public static List <double> GetLinearRegression(REngine engine, double[] xdata, double[] ydata) { if (engine == null) { throw new Exception("REngine not instantiated."); } double a = 0, b = 0, c = 0; if (xdata.Length > 1 && xdata.Length == ydata.Length) { NumericVector group1 = engine.CreateNumericVector(xdata); NumericVector group2 = engine.CreateNumericVector(ydata); engine.SetSymbol("group1", group1); engine.SetSymbol("group2", group2); GenericVector t; t = engine.Evaluate("lm.r <- lm (group2 ~ group1)").AsList(); t = engine.Evaluate("coef(summary(lm.r))").AsList(); NumericVector r0 = t[0].AsNumeric(); //intercept estimate NumericVector r1 = t[1].AsNumeric(); //slope estimate NumericVector r2 = t[2].AsNumeric(); //intercept se NumericVector r3 = t[3].AsNumeric(); //slope se NumericVector r4 = t[4].AsNumeric(); //intercept tvalue NumericVector r5 = t[5].AsNumeric(); //slope t value NumericVector r6 = t[6].AsNumeric(); //intercept P>t NumericVector r7 = t[7].AsNumeric(); //slope P>t a = r1.First(); b = r3.First(); c = r0.First() + xdata[0] * r1.First(); } List <double> ld = new List <double> { }; ld.Add(a); ld.Add(b); ld.Add(c); return(ld); }
protected override double calculateComposite(double[][] objValues) { for (int i = 0; i < VariableNames.Length; i++) { rEngine.SetSymbol(VariableNames[i], rEngine.CreateNumericVector(objValues[i])); } Log.InfoFormat("Objective expression: {0}", ObjectiveExpression); return(rEngine.Evaluate(ObjectiveExpression).AsNumeric()[0]); }
private void BtR_OnClick(object sender, RoutedEventArgs e) { if (Open) { try { REngine.SetEnvironmentVariables(); REngine engine = REngine.GetInstance(); engine.Initialize(); engine.SetSymbol("x", engine.CreateNumericVector(X)); engine.SetSymbol("y", engine.CreateNumericVector(Y)); engine.Evaluate("plot(x, y, type = 'l', main = 'Дискретный вариационный ряд')"); } catch { MessageBox.Show("RGUI.exe не найден!", "Ошибка"); } } }
public void Run() { if (_targetInstrumentName == null || _matchInstrumentName == null || _targetSampleList == null || _matchSampleList == null) { throw new ArgumentNullException("参数未设置"); } engine.SetSymbol("target", engine.CreateCharacter(_targetInstrumentName)); engine.SetSymbol("match", engine.CreateCharacter(_matchInstrumentName)); engine.SetSymbol("filename", engine.CreateCharacter(_imagePath)); engine.SetSymbol("检测系统A结果", engine.CreateNumericVector(_targetSampleList)); engine.SetSymbol("检测系统B结果", engine.CreateNumericVector(_matchSampleList)); engine.Evaluate("source('" + _scriptPath + "')"); }
private async Task <TTestGroupsDTO> CreateGroupsForTTest(BusinessKey businessKey) { var rawData = await _oppeDBService.GetRawDataFactList(businessKey); if (!rawData.Any()) { return(null); } var grp1 = Array.ConvertAll(rawData.Where(r => r.Name == "Peers").Select(r => r.Value).ToArray(), x => (double)x); var grp2 = Array.ConvertAll(rawData.Where(r => r.Name != "Peers").Select(r => r.Value).ToArray(), x => (double)x); var tTestGroupsDto = new TTestGroupsDTO { Group1 = _engine.CreateNumericVector(grp1), Group2 = _engine.CreateNumericVector(grp2) }; return(tTestGroupsDto); }
public static void Start(REngine engine) { Console.WriteLine("\n\nExporting Objects\n\n"); string RCodeString = string.Empty; //R character vector -- R.NET RDotNet.RDotNet.CharacterVector Console.WriteLine("\nR character vector\n"); string[] myStringArray = new string[] { "PIDataLink", "PIProcessBook", "PIWebParts" }; CharacterVector myCharacterVector = engine.CreateCharacterVector(myStringArray.AsEnumerable()); engine.SetSymbol("mycharvector", myCharacterVector); engine.Evaluate("print(mycharvector)"); //R integer vector -- R.NET RDotNet.NumericVector Console.WriteLine("\nR int vector\n"); int[] myIntegerArray = new int[] { 4, 6, 10, 140, 54, 25 }; IntegerVector myIntegerVector = engine.CreateIntegerVector(myIntegerArray); engine.SetSymbol("myintvector", myIntegerVector); engine.Evaluate("print(myintvector)"); //R real vector -- R.NET RDotNet.NumericVector Console.WriteLine("\nR real vector\n"); NumericVector myNumericVector = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 }); engine.SetSymbol("mynumvector", myNumericVector); engine.Evaluate("print(mynumvector)"); //R complex vector -- R.NET RDotNet.ComplexVector Console.WriteLine("\nR complex vector\n"); Complex[] myComplexArray = new Complex[] { Complex.FromPolarCoordinates(10, 0.524), new Complex(12, 6), new Complex(14, 3), (Complex)12.3m, Complex.One + Complex.One }; ComplexVector myComplexVector = engine.CreateComplexVector(myComplexArray); engine.SetSymbol("mycomplexvector", myComplexVector); engine.Evaluate("print(mycomplexvector)"); //R raw vector -- R.NET RDotNet.RawVector Console.WriteLine("\nR raw vector\n"); byte[] myByteArray = System.Text.Encoding.ASCII.GetBytes("u03a0"); RawVector myRawVector = engine.CreateRawVector(myByteArray); engine.SetSymbol("myrawvector", myRawVector); engine.Evaluate("print(myrawvector)"); //R logical vector -- R.NET RDotNet.LogicalVector Console.WriteLine("\nR logical vector\n"); LogicalVector myLogicalVector = engine.CreateLogicalVector(new Boolean[] { true, false, false, false, true }); engine.SetSymbol("mylogicalvector", myLogicalVector); engine.Evaluate("print(mylogicalvector)"); }
public static void Birth_of_age(this REngine engine) { var numVer = engine.CreateNumericVector(new double[] { 11, 30, 39, 20 }); var charVer = engine.CreateCharacterVector(new string[] { "70后", "80后", "90后", "00后" }); engine.SetSymbol("x", numVer); engine.SetSymbol("labels", charVer); engine.Evaluate("png(file = 'birth_of_age.jpg')"); engine.Evaluate("pie(x,labels)"); engine.Evaluate("dev.off()"); }