private void MakePtfReport(string[] input_files, string path_out, string report_name) { // make sure we start in the correct directory with a clean environment engine.Evaluate("rm(list=ls())"); engine.Evaluate("gc()"); engine.Evaluate("setwd('C:/Users/Keiran/Documents/Backtest_Source/R')"); // pass pnl files into R CharacterVector r_input_files = engine.CreateCharacterVector(input_files); engine.SetSymbol("filenames", r_input_files); // output directory CharacterVector r_path_out = engine.CreateCharacterVector(new string[] { path_out }); engine.SetSymbol("path.out", r_path_out); // report name CharacterVector r_filestem = engine.CreateCharacterVector(new string[] { report_name }); engine.SetSymbol("filestem", r_filestem); // pass in dates and flags LogicalVector r_relrtns = engine.CreateLogicalVector(new bool[] { relative_returns }); engine.SetSymbol("rel.rtns", r_relrtns); CharacterVector r_startEndDate = engine.CreateCharacterVector(new string[] { date_start.ToShortDateString(), date_end.ToShortDateString() }); engine.SetSymbol("start.end.dates", r_startEndDate); // 2. sanity checks engine.Evaluate("print(rel.rtns)"); engine.Evaluate("print(start.end.dates)"); engine.Evaluate("print(filenames)"); engine.Evaluate("print(path.out)"); engine.Evaluate("print(filestem)"); // 3. run R script to make daily pnl engine.Evaluate("source('PortfolioMakeReport.R')"); // 4. copy pdf report to output directory string pdffile = report_name + ".pdf"; string pdffile_orig = System.IO.Path.Combine(@"C:\Temp\TeX_Tmp\", pdffile); pdffile_dest = System.IO.Path.Combine(path_out, pdffile); File.Copy(pdffile_orig, pdffile_dest, true); // 5. copy daily and monthly pnl files to output directory string daily_file = report_name + "_pnl_daily.csv"; string daily_file_orig = System.IO.Path.Combine(@"C:\Temp\TeX_Tmp\", daily_file); string daily_file_dest = System.IO.Path.Combine(path_out, daily_file); File.Copy(daily_file_orig, daily_file_dest, true); string monthly_file = report_name + "_pnl_monthly.csv"; string monthly_file_orig = System.IO.Path.Combine(@"C:\Temp\TeX_Tmp\", monthly_file); string monthly_file_dest = System.IO.Path.Combine(path_out, monthly_file); File.Copy(monthly_file_orig, monthly_file_dest, true); }
//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 ClusteringMethKMean(List <int> activeVariables) { string clust_kmean = tmpFolder + "clust_kmean.png"; CharacterVector fileNameVector = engine.CreateCharacterVector(new[] { clust_kmean }); engine.SetSymbol("clust_kmean", fileNameVector); engine.Evaluate("library(cluster)"); engine.Evaluate("library(ggplot2)"); string clusVar = ""; for (int k = 0; k < activeVariables.Count; k++) { clusVar += ((1 + activeVariables[k]).ToString()) + ","; } clusVar = clusVar.Substring(0, clusVar.Length - 1); engine.Evaluate("corV <- c(" + clusVar + ")"); engine.Evaluate("kclust <- kmeans(as.matrix(dataset[, corV]), centers = 9)"); engine.Evaluate("png(filename=clust_kmean, width=6, height=6, units='in', res=100)"); engine.Evaluate("clusplot(dataset[,corV], kclust$cluster, main='K-Mean', xlab = \"\", ylab = \"Height\" , color=TRUE, shade=TRUE, labels=2, lines=0)"); engine.Evaluate("dev.off()"); worddoc.InlineShapes.AddPicture(clust_kmean, false, true, wrange); latexText += "\n\\begin{frame}\\frametitle{K-Mean}" + "\n \\begin{figure}" + "\n \\centering" + "\n \\includegraphics[scale=0.48]{clust_kmean.png}" + "\n \\caption{K-Mean}" + "\n \\end{figure}" + "\n\\end{frame}"; }
public void Initialize(string[] tickers, string startDate) { CharacterVector tickerVector = _engine.CreateCharacterVector(tickers); CharacterVector dateVector = _engine.CreateCharacterVector(new[] { startDate }); var appendedTickers = tickers.Select(ticker => $"NASDAQ:{ticker}").ToArray(); CharacterVector nasdaqCharacterVector = _engine.CreateCharacterVector(appendedTickers); _engine.SetSymbol("nasdaqCharacterVector", nasdaqCharacterVector); _engine.Evaluate("tickers.temp = spl(nasdaqCharacterVector)"); _engine.SetSymbol("dateVector", dateVector); _engine.SetSymbol("tickerVector", tickerVector); _engine.Evaluate("tickers = spl(tickerVector)"); _engine.Evaluate("data.fund <- new.env()"); _engine.Evaluate( "for (i in 1:len(tickers)) {data.fund[[tickers[i]]] = fund.data(tickers.temp[i], 80, 'annual')};"); _engine.Evaluate("data <- new.env()"); _engine.Evaluate("getSymbols(tickers, src = 'yahoo', from = '1970-01-01', env = data, auto.assign = T)"); _engine.Evaluate("for (i in ls(data)) {data[[i]] = adjustOHLC(data[[i]], use.Adjusted = T)};"); _engine.Evaluate("portfolioPrices <- NULL"); _engine.Evaluate("for (Ticker in tickers) {" + $"portfolioPrices <- cbind(portfolioPrices, getSymbols.yahoo(Ticker, from={startDate}, periodicity = \"daily\", auto.assign=FALSE)[,3])" + "}"); }
private static void TestPendingFinalizersThreadingIssues(REngine e) { e.Evaluate("f <- function(a) {if (length(a)!= 1) stop('What goes on?')}"); var f = e.Evaluate("f").AsFunction(); try { e.Evaluate("f(letters[1:3])"); } catch (EvaluationException) { } f.Invoke(e.CreateCharacterVector(new[] { "blah" })); try { f.Invoke(e.CreateCharacterVector(new[] { "blah", "blah" })); } catch (EvaluationException) { Console.WriteLine("Caught the expected exception"); } f = null; GC.Collect(); GC.WaitForPendingFinalizers(); e.Dispose(); Console.WriteLine("Just waiting for crash..."); GC.Collect(); GC.WaitForPendingFinalizers(); }
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)); }
/// <summary> /// Test that the disposal of the REngine and program exit does not lead to an exception. /// Primarily for testing an issue with Debian: https://rdotnet.codeplex.com/workitem/60 /// </summary> private static void Main(string[] args) { bool keepSexpRefAfterDispose = false; if (args.Length > 0) { keepSexpRefAfterDispose = bool.Parse(args[0]); } REngine.SetEnvironmentVariables(); REngine e = REngine.GetInstance(); e.Evaluate("f <- function(a) {if (length(a)!= 1) stop('What goes on?')}"); var f = e.Evaluate("f").AsFunction(); try { e.Evaluate("f(letters[1:3])"); } catch (EvaluationException) { } f.Invoke(e.CreateCharacterVector(new[] { "blah" })); try { f.Invoke(e.CreateCharacterVector(new[] { "blah", "blah" })); } catch (EvaluationException) { Console.WriteLine("Caught the expected exception"); } if (!keepSexpRefAfterDispose) { Console.WriteLine("Symbolic expression set to null before engine Dispose"); f = null; } GC.Collect(); GC.WaitForPendingFinalizers(); e.Dispose(); Console.WriteLine("Engine has been disposed of"); if (keepSexpRefAfterDispose) { Console.WriteLine("Symbolic expression set to null after engine Dispose"); f = null; } Console.WriteLine("Now performing final CLR GC collect"); GC.Collect(); GC.WaitForPendingFinalizers(); }
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) { //intializing setPath(); loadData(); using (REngine rengine = REngine.GetInstance()) { rengine.Initialize(); //Importing libraries rengine.Evaluate("library(ggplot2)"); rengine.Evaluate("library(ggthemes)"); rengine.Evaluate("library(dplyr)"); //Creating the dataframe rengine.Evaluate("df <- setNames(data.frame(matrix(ncol=2, nrow=0)), c(\"year\",\"userCount\"))").AsDataFrame(); //Storing data from the class object into the dataframe for (int i = 0; i < holder.year.Count; i++) { rengine.Evaluate("df[nrow(df)+1,] <- c(" + holder.year[i] + ", " + holder.userCount[i] + ")"); } //Creating the time series chart rengine.Evaluate("chart <- df %>% ggplot(aes(x=year, y=userCount)) + geom_smooth(size=2, aes(colour=\"red\", fill=\"black\"), show.legend=FALSE) + labs(x=\"Year\",y=\"User Count\") + theme_classic()"); //Saving the graph to a png file string fileName = "C:/Users/{insert username here}/Desktop/plot0.png"; CharacterVector fileVector = rengine.CreateCharacterVector(new[] { fileName }); rengine.SetSymbol("fileName", fileVector); rengine.Evaluate("png(filename=fileName, width=6, height=6, units='in',res=100)"); rengine.Evaluate("print(chart)"); //Cleaning up rengine.Evaluate("dev.off()"); rengine.Dispose(); } }
public void Analyse(List <string> inputTweets) { REngine.SetEnvironmentVariables(); REngine engine = REngine.GetInstance(); try { inputTweets.ForEach(x => RCharVector.AddRange(x.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries))); inputTweets.ForEach(x => RCharVector.RemoveAll(y => string.IsNullOrEmpty(y.Trim()))); if (inputTweets.Count > 0) { engine.Evaluate("library('syuzhet')"); CharacterVector gp3 = engine.CreateCharacterVector(RCharVector); engine.SetSymbol("grp3", gp3); engine.Evaluate("grp3"); engine.Evaluate("g <- get_nrc_sentiment(grp3)"); engine.Evaluate("barplot(colSums(prop.table(g[, 3:8])))"); } else { Console.WriteLine("No Tweets found with input data. Please change input data."); } } finally { engine.Dispose(); } }
public async Task <IActionResult> Get() { //_rEngine.Evaluate("install.packages('forecast', dependencies = TRUE)"); //_rEngine.Evaluate("install.packages('lmtest', dependencies = TRUE)"); _rEngine.Evaluate("library(forecast)"); _rEngine.Evaluate("library(lmtest)"); string fileName = "myplot.png"; CharacterVector fileNameVector = _rEngine.CreateCharacterVector(new[] { fileName }); _rEngine.SetSymbol("fileName", fileNameVector); _rEngine.Evaluate("png(filename=fileName, width=6, height=6, units='in', res=100)"); _rEngine.Evaluate("vector <- as.numeric(AirPassengers)"); _rEngine.Evaluate("z <- ts(vector, frequency = 12, start = c(1949, 1))"); _rEngine.Evaluate("z_train <- ts(z[1:100], frequency = 12)"); _rEngine.Evaluate("z_validate <- ts(z[101:144], frequency = 12)"); _rEngine.Evaluate("fit <- Arima(y = z_train, order = c(1,1,0), seasonal = c(1,1,0), lambda = TRUE)"); _rEngine.Evaluate("predition <- forecast(fit, h = 44)"); //_rEngine.Evaluate("z_train <- ts(z[1:100], frequency = 12"); _rEngine.Evaluate("plot(predition)"); //plot and save file //_rEngine.Evaluate("lines(fit$fitted, col = 'blue')"); _rEngine.Evaluate("dev.off()"); Byte[] b = System.IO.File.ReadAllBytes(@"C:\Users\admin\source\repos\DataAnalisysApi\DataAnalisysApi\myplot.png"); // You can use your own method over here. return(File(b, "image/jpeg")); }
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++; } }
public void SetSymbolCharVector(string name, string[] value) { clsRCmdLog.LogRComment(string.Format("RdnConnectorClass.SetSymbolCharVector:{0}", name)); var sym = _engine.CreateCharacterVector(value); _engine.SetSymbol(name, sym); }
public void test_NextItem_P(int numofItems, ModelNames.Models paramModel, ModelNames.CriterionTypes paramCriterion) { resultFlag = true; REngine.SetEnvironmentVariables(); REngine engineObj = REngine.GetInstance(); // Loading a library from R engineObj.Evaluate("library(catR)"); // Polytomous Items CharacterVector modelName = engineObj.CreateCharacterVector(new string[] { paramModel.EnumToString() }); engineObj.SetSymbol("modelName", modelName); DataFrame PolyItems = engineObj.Evaluate("PolyItems <- genPolyMatrix(" + numofItems + ", 5, model = modelName, same.nrCat = TRUE)").AsDataFrame(); engineObj.SetSymbol("PolyItems", PolyItems); // Adapting with the existing "CAT-Items" type (Wrapper) Console.WriteLine("*******************************************"); Console.WriteLine("Polytomous Items, Model : " + paramModel.EnumToString()); Console.WriteLine("*******************************************"); CATItems itemBank = new CATItems(PolyItems[0].Length, paramModel.EnumToString(), 5); Tuple <CATItems.ColumnNames, int>[] cols = itemBank.GetKeys(); for (int i = 0; i < cols.Length; i++) { itemBank.SetItemParamter(cols[i], PolyItems[i].Select(y => (double)y).ToArray()); } // Call "NextItem" function from R GenericVector r_NextItem = engineObj.Evaluate("r_NextItem <- nextItem(PolyItems, model = modelName, theta = 0, criterion = \"" + paramCriterion.ToString() + "\")").AsList(); // Selected item NumericVector item = r_NextItem[0].AsNumeric(); DataFrame par = r_NextItem[1].AsDataFrame(); // Value of "info" NumericVector thStart = r_NextItem[2].AsNumeric(); // Criterion CharacterVector startSelect = r_NextItem[3].AsCharacter(); // Call "NextItem" function from CS NextItemModel cs_NextItem = CatRLib.NextItem(itemBank, model: paramModel.EnumToString(), theta: 0, criterion: (int)paramCriterion); //Test passed for "MFI" if (item[0] != cs_NextItem.item) { resultFlag = false; } Assert.IsTrue(resultFlag); }
public static void Barchart_stacked(this REngine engine) { //setwd("F:/worksp/R") //# Create the input vectors. //colors < -c("green", "orange", "brown") //months < -c("一月", "二月", "三月", "四月", "五月") //regions < -c("东部地区", "西部地区", "南部地区") //# Create the matrix of the values. //Values < -matrix(c(2, 9, 3, 11, 9, 4, 8, 7, 3, 12, 5, 2, 8, 10, 11), nrow = 3, ncol = 5, byrow = TRUE) //# Give the chart file a name. //png(file = "barchart_stacked.png") //# Create the bar chart. //barplot(Values, main = "总收入", names.arg = months, xlab = "月份", ylab = "收入", // col = colors) //# Add the legend to the chart. //legend("topleft", regions, cex = 1.3, fill = colors) //# Save the file. //dev.off() //var numVer = engine.CreateNumericVector(new double[] { 110, 300, 390, 200 }); var colors = engine.CreateCharacterVector(new string[] { "green", "orange", "brown" }); engine.SetSymbol("colors", colors); var regions = engine.CreateCharacterVector(new string[] { "东", "西", "南" }); engine.SetSymbol("regions", regions); var months = engine.CreateCharacterVector(new string[] { "一月", "二月", "三用", "四月" }); engine.SetSymbol("months", months); var va = engine.CreateNumericVector(new double[] { 2, 9, 3, 11, 9, 4, 8, 7, 3, 12, 5, 2, 8, 10, 11 }); engine.SetSymbol("mat", va); var values = engine.Evaluate("matrix(mat,nrow=3,ncol=4)"); engine.SetSymbol("values", values); engine.Evaluate("png(file = 'barchart_stacked.jpg')"); engine.Evaluate("barplot(values,names.arg=months,xlab='月份',ylab='收入',main='总收入',col=colors)"); engine.Evaluate("legend('topleft',regions,cex=1.3,fill=colors)"); engine.Evaluate("dev.off()"); }
public TSAnalyze () { InitializeComponent (); // There are several options to initialize thengine, but by default the following suffice: REngine engine = REngine.GetInstance(); //init the R engine REngine.SetEnvironmentVariables (); engine = REngine.GetInstance (); engine.Initialize (); //prepare data List<int> size = new List<int>() { 29, 33, 51, 110, 357, 45, 338, 543, 132, 70, 103, 301, 146, 10, 56, 243, 238 }; List<int> population = new List<int>() { 3162, 11142, 3834, 7305, 81890, 1339, 5414, 65697, 11280, 4589, 320, 60918, 480, 1806, 4267, 63228, 21327 }; var docPath = Directory.GetCurrentDirectory(); //var myDir = $@"{docPath}\output"; var myDir = bingPathToAppDir ("output"); Directory.CreateDirectory (myDir); Console.WriteLine (Directory.Exists (myDir)); Console.WriteLine (myDir); Console.WriteLine (bingPathToAppDir ("output")); Console.WriteLine ("my image location {0}", myDir); fileName = myDir + "\\myplot.png"; //calculate IntegerVector sizeVector = engine.CreateIntegerVector(size); engine.SetSymbol ("size", sizeVector); IntegerVector populationVector = engine.CreateIntegerVector(population); engine.SetSymbol ("population", populationVector); CharacterVector fileNameVector = engine.CreateCharacterVector(new[] { fileName }); engine.SetSymbol ("fileName", fileNameVector); engine.Evaluate ("reg <- lm(population~size)"); engine.Evaluate ("png(filename=fileName, width=6, height=6, units='in', res=100)"); engine.Evaluate ("plot(population~size)"); engine.Evaluate ("abline(reg)"); engine.Evaluate ("dev.off()"); //clean up engine.Dispose (); //output Console.WriteLine (""); Console.WriteLine ("Press any key to exit"); Console.ReadKey (); }
// GET api/values/5 public string Get(int id) { REngine engine = REngine.GetInstance(); CharacterVector charVec = engine.CreateCharacterVector(new[] { "Hello world" }); engine.SetSymbol("greetings", charVec); engine.Evaluate("str(greetings)"); string[] a = engine.Evaluate("'Hi there .NET, from the R engine'").AsCharacter().ToArray(); return(a[0]); }
public void SavePNG(List <string> kategorii) { string fileName; REngine.SetEnvironmentVariables(); REngine engine = REngine.GetInstance(); fileName = @"C:\Users\Daria\Desktop\kategorii.png"; CharacterVector fileNameVector = engine.CreateCharacterVector(new[] { fileName }); engine.SetSymbol("fileName", fileNameVector); CharacterVector kategorii_read = engine.CreateCharacterVector(kategorii); engine.SetSymbol("data", kategorii_read); engine.Evaluate("png(filename=fileName, width=800, height=600)"); engine.Evaluate("barplot(sort(table(data), decreasing = T), main = 'Kategorie książek', ylab = 'Liczba', col = 'steelblue', border = NA, las=2)"); engine.Evaluate("dev.off()"); }
public void RTest() { // 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"); }
static void Main(string[] args) { // Sample code used for updating the documentation at the codeplex web site. using (REngine engine = REngine.GetInstance()) { var e = engine.Evaluate("x <- 3"); // You can now access x defined in the R environment. NumericVector x = engine.GetSymbol("x").AsNumeric(); engine.Evaluate("y <- 1:10"); NumericVector y = engine.GetSymbol("y").AsNumeric(); // Invoking functions; Previously you may have needed custom function definitions var myFunc = engine.Evaluate("function(x, y) { expand.grid(x=x, y=y) }").AsFunction(); var v1 = engine.CreateIntegerVector(new[] { 1, 2, 3 }); var v2 = engine.CreateCharacterVector(new[] { "a", "b", "c" }); var df = myFunc.Invoke(new SymbolicExpression[] { v1, v2 }).AsDataFrame(); // As of R.NET 1.6, more function call syntaxes are supported. var expandGrid = engine.Evaluate("expand.grid").AsFunction(); var d = new Dictionary <string, SymbolicExpression>(); d["x"] = v1; d["y"] = v2; df = expandGrid.Invoke(d).AsDataFrame(); // querying data frames engine.SetSymbol("cases", df); // As of R.NET 1.6, factor to character expressions work consistently with R var letterCases = engine.Evaluate("cases[,'y']").AsCharacter().ToArray(); // "a","a","a","b","b","b", etc. Same as as.character(cases[,'y']) in R // This used to return "1", "1", "1", "2", "2", etc. with R.NET 1.5.5 // Equivalent: letterCases = df[1].AsCharacter().ToArray(); letterCases = df["y"].AsCharacter().ToArray(); // Accessing items by two dimensional indexing string s = (string)df[1, 1]; // "a" s = (string)df[3, 1]; // "a" s = (string)df[3, "y"]; // "b" // s = (string)df["4", "y"]; // fails because there are no row names df[3, "y"] = "a"; s = (string)df[3, "y"]; // "a" df[3, "y"] = "d"; s = (string)df[3, "y"]; // null, because we have an <NA> string in R // invoking a whole script // engine.Evaluate("source('c:/src/path/to/myscript.r')"); // TODO // Date-time objects } }
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()"); }
public string run_ruvseq(List <string> group1, List <string> group2) { try { engine = REngine.GetInstance(); engine.Initialize(); engine.Evaluate(string.Format("Sys.setenv(PATH = paste('{0}', ';', Sys.getenv('PATH'), sep=''))", this.rPath)); engine.Evaluate("Sys.getenv()"); engine.Evaluate("library('RUVSeq')"); engine.Evaluate("library('DESeq2')"); engine.Evaluate("library('RColorBrewer')"); engine.Evaluate("matrix <- read.table('" + inputFile + "', header=TRUE, sep=',', fill=TRUE, row.names=1)"); engine.Evaluate("matrix <- matrix + 1;" + "matrix <- round(matrix, 0);" + "filter <- apply(matrix, 1, function(x) length(x[x > 5]) >= 2);" + "filtered <- matrix[filter,];" + "genes <- rownames(filtered)[grep('^ENS', rownames(filtered))];" + "spikes <- rownames(filtered)[grep('^ERCC', rownames(filtered))];"); CharacterVector colnames = engine.Evaluate("colnames(filtered)").AsCharacter(); var x = engine.CreateCharacterVector(this.groupSeparation(colnames, group1, group2)); engine.SetSymbol("x", x); engine.Evaluate("print(x)"); engine.Evaluate("print(colnames(filtered))"); engine.Evaluate("colors <- brewer.pal(4, 'Set1');" + "set <- newSeqExpressionSet(as.matrix(filtered), phenoData = data.frame(x, row.names=colnames(filtered)));" + "set <- betweenLaneNormalization(set, which='upper');" + "set1 <- RUVg(set, spikes, k=1);" + "write.csv(normCounts(set1), paste('" + outputFileDirectory + "\\\\" + outputFile + "','_normalizedCounts.csv', sep=''));" + "write.csv(counts(set1), paste('" + outputFileDirectory + "\\\\" + outputFile + "', '_counts.csv', sep = ''));" + "write.csv(pData(set1), paste('" + outputFileDirectory + "\\\\" + outputFile + "','_colData.csv', sep = ''));"); engine.Evaluate(@"png(file = paste('" + outputFileDirectory + "\\\\" + outputFile + "','_graphRLE_RUV.png', sep = ''), height = 720, width = 1280);" + "plotRLE(set1, outline = FALSE, ylim = c(-4, 4), col = colors[x], xaxt = 'n', ann = FALSE);" + "text(x = seq(1, length(colnames(filtered))) - .2, par('usr')[3] - .4, labels = colnames(filtered), adj = c(1.5, 1.5), srt = 60, pos = 1, xpd = TRUE, cex = 1);" + "axis(1, at = seq(1, length(colnames(filtered)), by = 1), labels = FALSE);" + "dev.off();"); engine.Evaluate("png(file = paste('" + outputFileDirectory + "\\\\" + outputFile + "', '_graphPCA_RUV.png', sep = '), height = 720, width = 1280);" + "plotPCA(set1, col = colors[x], cex = 1.2);" + "dev.off();"); return("Success"); } catch (RDotNet.EvaluationException e) { return(e.ToString()); } finally { engine.Evaluate("rm(list = ls())"); engine.Evaluate(@"detach(); detach(); detach();"); } }
private void button1_Click(object sender, EventArgs e) { REngine.SetEnvironmentVariables(); // <-- 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"); engine.Dispose(); }
public static SymbolicExpression ToExternalPointer(REngine engine, object instance) { if (instance == null) { return(engine.NilValue); } var tag = engine.CreateCharacterVector(new[] { NET_OBJ_TAG, instance.GetType().FullName }); var ptr = engine.GetFunction <R_MakeExternalPtr>()( Marshal.GetIUnknownForObject(instance), tag.DangerousGetHandle(), engine.NilValue.DangerousGetHandle()); var sexp = engine.CreateFromNativeSexp(ptr); return(sexp); }
private bool SetVariableInR(DataTable dt, DateTime startDate, DateTime endDate) { _rEngine.Evaluate(string.Format("{0} <- data.frame()", _IRType)); DataColumn date = dt.Columns.Cast <DataColumn>().First(col => col.DataType == typeof(DateTime)); dt.Rows.Cast <DataRow>().OrderByDescending(row => row[date]); var dates = from row in dt.Rows.Cast <DataRow>() where (DateTime)row[date] >= startDate && (DateTime)row[date] <= endDate select((DateTime)row[date]).ToShortDateString(); if (dates.Count() == 0) { using (new CenterWinDialog(Application.OpenForms.Cast <Form>().Last())) { MessageBox.Show("Data is not available on the selecte time range.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(false); } CharacterVector dateVector = _rEngine.CreateCharacterVector(dates); _rEngine.SetSymbol(date.ColumnName, dateVector); _rEngine.Evaluate(string.Format(@"{0} <- as.Date({0}, ""%m/%d/%Y"")", date.ColumnName)); foreach (DataColumn dc in dt.Columns) { switch (dc.DataType.ToString()) { case "System.Double": var templs = from row in dt.Rows.Cast <DataRow>() where (DateTime)row[date] >= startDate && (DateTime)row[date] <= endDate select row[dc].GetType() == typeof(DBNull) ? double.NaN : (double)row[dc]; NumericVector tempvec = _rEngine.CreateNumericVector(templs); _rEngine.SetSymbol(dc.ColumnName, tempvec); _rEngine.Evaluate(string.Format(@"{0} <- data.frame(Date={1}, Value={2}, Level=""{3}"")", "tempDF", date.ColumnName, dc.ColumnName, dc.ColumnName)); _rEngine.Evaluate("tempDF"); _rEngine.Evaluate(string.Format(@"{0} <- rbind.data.frame({1}, {2})", _IRType, _IRType, "tempDF")); break; } } return(true); }
public void helloworld() { REngine.SetEnvironmentVariables(); // <-- 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(); log.Debug("R answered: '" + a[0].ToString() + "'"); log.Debug("Press any key to exit the program"); engine.Dispose(); }
private async Task <LeveneTestDTO> CreateGroupsForLevene(BusinessKey businessKey) { var rawData = await _oppeDBService.GetRawDataFactList(businessKey); if (!rawData.Any()) { return(null); } var namesV = rawData.Select(l => l.Name).ToArray(); var values = Array.ConvertAll(rawData.Select(l => l.Value).ToArray(), x => (double)x); LeveneTestDTO leveneTestDTO = new LeveneTestDTO { Names = _engine.CreateCharacterVector(namesV), Values = _engine.CreateNumericVector(values) }; return(leveneTestDTO); }
static void RService() { REngine.SetEnvironmentVariables(); // <-- May be omitted; the next line would call it. REngine engine = REngine.GetInstance(); // A somewhat contrived but customary Hello World: var e = engine.Evaluate("x <- 3"); NumericVector x = engine.GetSymbol("x").AsNumeric(); engine.Evaluate("y <- 1:10"); NumericVector y = engine.GetSymbol("y").AsNumeric(); 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(); }