예제 #1
0
        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();
        }
예제 #2
0
 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();
     }
 }
예제 #3
0
        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();
        }
예제 #4
0
        public void testR()
        {
            string  result;
            string  input;
            REngine engine;

            //init the R engine
            REngine.SetEnvironmentVariables();
            engine = REngine.GetInstance();
            engine.Initialize();

            //input
            Console.WriteLine("Please enter the calculation");
            // input = Console.ReadLine();
            input = " 1 + 2";
            //calculate
            CharacterVector vector = engine.Evaluate(input).AsCharacter();

            result = vector[0];

            //clean up
            engine.Dispose();

            //output
            Console.WriteLine("");
            Console.WriteLine("Result: '{0}'", result);
            Console.WriteLine("Press any key to exit");
            // Console.ReadKey();
        }
예제 #5
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);


            string rHome = Path.Combine(Directory.GetCurrentDirectory(), @"R-portable");

            Environment.SetEnvironmentVariable("PATH", rHome);
            REngine engine = REngine.GetInstance();

            Application.ThreadExit += (sender, e) => engine.Dispose();
            engine.Initialize();

            var ImageLocation = Path.Combine(Path.GetTempPath(), Path.GetTempFileName() + ".png");

            Application.ThreadExit += (sender, e) => {
                try
                {
                    File.Delete(ImageLocation);
                }
                finally { }
            };
            var outGraphForm = new Form1();

            outGraphForm.pictureBox1.ImageLocation = ImageLocation;
            engine.Evaluate(string.Format("png('{0}', {1}, {2})", ImageLocation.Replace('\\', '/'),
                                          outGraphForm.pictureBox1.Width, outGraphForm.pictureBox1.Height));
            engine.Evaluate(@"plot(1:10, pch=1:10, col=1:10, cex=seq(1, 2, length=10))
                  text(c(1), c(1), c('Text here'), col=c('red'))");
            engine.Evaluate("dev.off()");
            Application.Run(outGraphForm);
        }
예제 #6
0
        /// <summary>
        /// 测试不成功,slam要求R Version >= 3.4.0
        /// </summary>
        private static void TestImage()
        {
            try
            {
                REngine.SetEnvironmentVariables(@"D:\r\R-3.2.5\bin\i386", @"D:\r\R-3.2.5\bin\i386");
                REngine engine = REngine.GetInstance();
                engine.Initialize();

                var x = engine.Evaluate("jpeg('test.jpg',quality=90)");
                engine.Evaluate("library(wordcloud)");
                engine.Evaluate("colors=c('red','blue','green','yellow','purple')");
                engine.Evaluate(" data(SOTU);wordcloud(SOTU,min.freq=10,colors=colors);dev.off()");
                x = engine.Evaluate("r=readBin('test.jpg','raw',3000*3000);unlink('test.jpg');r");

                byte[] bs  = x.AsRaw().ToArray();
                Image  img = Image.FromStream(new MemoryStream(bs));
                img.Save("e:/my.jpg", ImageFormat.Jpeg);

                engine.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
        }
예제 #7
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine(@"Usage:");
                Console.WriteLine(@"SourceRCode.exe c:/path/to/source.r");
                Console.WriteLine(@" (!) Do note that you should use forward slashes (simpler than backslashes here)");
                return;
            }
            REngine.SetEnvironmentVariables();
            REngine engine = REngine.GetInstance();

            engine.Evaluate("source('" + args[0] + "')");

            /*
             * // Say your R file contains:
             *
             * sqr <- function(x) {
             * return(x*x)
             * }
             */
            Console.WriteLine("By default, autoprint on the console");
            double[] a = engine.Evaluate("sqr(0:5)").AsNumeric().ToArray();

            Console.WriteLine("However, for manipulation of larger data, autoprint on the console is probably not a good idea");
            engine.AutoPrint = false;
            a = engine.Evaluate("sqr(0:1000)").AsNumeric().ToArray();

            Console.WriteLine("Length(a) is " + a.Length + ", but the vector has not been written out to the console");
            Console.WriteLine("Press any key to exit the program");
            Console.ReadKey();
            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);
        }
예제 #9
0
 /// <summary>
 /// Zamyka instancję. Przed zamknięciem aplikacji zawsze zamykać instancję!
 /// </summary>
 public void DisposeEngine()
 {
     if (engine != null)
     {
         engine.Dispose();
     }
 }
예제 #10
0
        public static void HelloR()
        {
            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 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();
        }
예제 #11
0
파일: Program.cs 프로젝트: koson/C-sharp-R
        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();
        }
예제 #12
0
        /// <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();
        }
예제 #13
0
        public void Rexecution()
        {
            //RScriptRunner rr = new RScriptRunner();
            //string curDirectory = "D:\\VisualStudioCommunity\\DailyMonitoringCMC\\DailyMonitoringCMC\\App_Data";
            //string result = RScriptRunner.RunFromCmd(curDirectory + @"\testCSharp.R", "rscript.exe","");
            //@"C:\Program Files\R\R-3.2.3\bin\x64", @"C:\Program Files\R\R-3.2.3"
            //IMPORTANT: Engine.evaluate("source('\\\\\\\\something.x.y./somelocation/somefile.r');");

            REngine.SetEnvironmentVariables();
            // There are several options to initialize the engine, but by default the following suffice:
            REngine engine = REngine.GetInstance();

            //engine.Evaluate("require('ggplot2')");
            //engine.Evaluate("library('ggplot2')");
            engine.Evaluate("print(plot.ts(c(1:100))");
            //engine.Evaluate("source('D:\\Thesis R\\testCSharp.R')");

            // .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 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();
            }
        }
예제 #15
0
        //
        // 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());
        }
예제 #16
0
        private static void Main(string[] args)
        {
            string rHome = null;
            string rPath = null;

            if (args.Length > 0)
            {
                rPath = args[0];
            }
            if (args.Length > 1)
            {
                rHome = args[1];
            }

            REngine.SetEnvironmentVariables(rPath: rPath, rHome: rHome);
            REngine e = REngine.GetInstance();

            System.Console.WriteLine(RDotNet.NativeLibrary.NativeUtility.SetEnvironmentVariablesLog);

            counter = 0;
            for (int i = 0; i < 6; i++)
            {
                TestDataFrameInMemoryCreation(e);
            }

            for (int i = 0; i < 6; i++)
            {
                TestCallStop(e);
            }

            e.Dispose();
        }
예제 #17
0
파일: Clustering.cs 프로젝트: Pribina91/SAM
        void init()
        {
            REngine engine = REngine.GetInstance();

            engine.Initialize();

            engine.Dispose();
        }
예제 #18
0
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            // you should always dispose of the REngine properly.
            // After disposing of the engine, you cannot reinitialize nor reuse it
            REngine engine = REngine.GetInstance();

            engine.Dispose();
        }
예제 #19
0
 private static void KillEngine()
 {
     if (_engine != null)
     {
         // you should always dispose of the REngine properly.
         // After disposing of the engine, you cannot reinitialize nor reuse it
         _engine.Dispose();
     }
 }
예제 #20
0
        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 ();



            }
예제 #21
0
        private static void Main(string[] args)
        {
            string rHome = null;
            string rPath = null;

            if (args.Length > 0)
            {
                rPath = args[0];
            }
            if (args.Length > 1)
            {
                rHome = args[1];
            }

            NativeUtility util = new NativeUtility();

            Console.WriteLine(util.FindRPaths(ref rPath, ref rHome));

            rHome = null;
            rPath = null;

            REngine.SetEnvironmentVariables(rPath: rPath, rHome: rHome);
            REngine e = REngine.GetInstance();

            Console.WriteLine(NativeUtility.SetEnvironmentVariablesLog);

            TestIssue53(e, 1000000);
            e.Dispose();
            return;

            counter = 0;
            for (int i = 0; i < 6; i++)
            {
                TestDataFrameInMemoryCreation(e);
            }

            for (int i = 0; i < 6; i++)
            {
                TestCallStop(e);
            }

            e.Dispose();
        }
예제 #22
0
        public static void Main(string[] args)
        {
            REngine.SetEnvironmentVariables();
            REngine engine = REngine.GetInstance();

            rdotnet_discussions_646729(engine);
            // you should always dispose of the REngine properly.
            // After disposing of the engine, you cannot reinitialize nor reuse it
            engine.Dispose();
        }
예제 #23
0
        static void Main(string[] args)
        {
            REngine.SetEnvironmentVariables();
            // There are several options to initialize the engine, but by default the following suffice:
            REngine engine = REngine.GetInstance();

            //engine.Birth_of_age();

            //engine.Age_title_colours();

            //engine.Barchart();
            //engine.barchart_months_revenue();
            //engine.Barchart_stacked();

            engine.SetWd();
            engine.GetWd();
            //engine.Print("开始安装exec组件");
            //engine.Evaluate("install.packages('xlsx')");
            //engine.Print("结束安装exec组件");


            engine.Print("读取文件开始");

            //var csvName = engine.ReadCsv("InputName.csv");

            //var param = new SymbolicExpressionParamList() { IsUseParamName = false };
            //param.Add(new SymbolicExpressionParam(csvName));
            //param.Add(new SymbolicExpressionParam(where: " as.Date(start_date) > as.Date('2014-01-01') "));
            ////param.Add(new SymbolicExpressionParam(where: "salary>600&dept=='IT'"));
            //var subset = engine.ExecFunction(param, "subset");

            //var paramA = new SymbolicExpressionParamList() { IsUseParamName = false };
            //paramA.Add(new SymbolicExpressionParam(subset.AsDataFrame()));
            //paramA.Add(new SymbolicExpressionParam(where: "'output1.csv'"));
            //paramA.Add(new SymbolicExpressionParam(where: "row.names = FALSE"));
            //engine.ExecFunction(paramA, "write.csv");
            //engine.ReadCsv("output1.csv");

            engine.Evaluate("library(xlsx) ");
            var paramA = new SymbolicExpressionParamList()
            {
                IsUseParamName = false
            };

            paramA.Add(new SymbolicExpressionParam(where : "'input.xlsx'"));
            paramA.Add(new SymbolicExpressionParam(engine.CreateNumeric(1), paramName: "sheetIndex"));
            engine.ExecFunction(paramA, "read.xlsx");
            //engine.ReadCsv("output1.csv");

            engine.Print("读取文件结束");

            engine.Dispose();

            Console.ReadKey();
        }
예제 #24
0
 /// <summary>
 ///   Releases unmanaged and - optionally - managed resources
 /// </summary>
 /// <param name="disposing"> <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources. </param>
 protected override void Dispose(bool disposing)
 {
     if (!disposed)
     {
         if (disposing)
         {
             rEngine.Dispose();
         }
         disposed = true;
     }
 }
예제 #25
0
        public static void Main(string[] args)
        {
            REngine.SetEnvironmentVariables();
            REngine engine = REngine.GetInstance();

            //stackoverflow_27689786_2752565 (engine);
            stackoverflow_27597542_2752565(engine);
            // you should always dispose of the REngine properly.
            // After disposing of the engine, you cannot reinitialize nor reuse it
            engine.Dispose();
        }
예제 #26
0
        private static void TestRVersion()
        {
            REngine.SetEnvironmentVariables(@"D:\r\R-3.2.5\bin\i386", @"D:\r\R-3.2.5\bin\i386"); // <-- May be omitted; next line would call it.
            REngine engine = REngine.GetInstance();

            string[] version    = engine.Evaluate("R.version.string").AsCharacter().ToArray();
            string   versionStr = string.Join("", version);

            Console.WriteLine(versionStr);
            engine.Dispose();
        }
예제 #27
0
        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();
        }
예제 #28
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine(@"Usage:");
                Console.WriteLine(@"SourceRCode.exe c:/path/to/source.r");
                Console.WriteLine(@" (!) Do note that you should use forward slashes (simpler than backslashes here)");
                return;
            }
            REngine.SetEnvironmentVariables();
            REngine engine = REngine.GetInstance();

            engine.Evaluate("source('" + args[0] + "')");

            /*
             * // Say your R file contains:
             *
             * sqr <- function(x) {
             * return(x*x)
             * }
             */
            Console.WriteLine("By default, autoprint on the console");
            double[] a = engine.Evaluate("sqr(0:5)").AsNumeric().ToArray();

            Console.WriteLine("However, for manipulation of larger data, autoprint on the console is probably not a good idea");
            engine.AutoPrint = false;
            a = engine.Evaluate("sqr(0:1000)").AsNumeric().ToArray();

            Console.WriteLine("Length(a) is " + a.Length + ", but the vector has not been written out to the console");

            /*
             * // if testing for http://stackoverflow.com/questions/32236596/calling-user-defined-functions-inside-a-script-in-r-net
             * double value1 = 1, value2 = 2;
             * var dataframe = engine.Evaluate(string.Format(
             *                                          CultureInfo.InvariantCulture,
             *                                          "dataframe <- userDefinedFunctionOne(parameter1 = {0}, parameter2 = {1})",
             *                                          value1,
             *                                          value2)).AsDataFrame();
             * // with
             * // userDefinedFunctionOne <- function(parameter1, parameter2) {
             * //    return( data.frame(a=parameter1, b=parameter2) )
             * // }
             *
             */

            Console.WriteLine("Press any key to exit the program");
            Console.ReadKey();
            engine.Dispose();
        }
예제 #29
0
 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.Dispose();
     }
 }
예제 #30
0
        /// <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();
        }