Пример #1
0
        //private  DataTable ReadCVS(string filepath, string filename)
        //{
        //    //string cvsDir = filepath;//要读取的CVS路径
        //    DataTable dt = new DataTable();
        //    if (filename.Trim().ToUpper().EndsWith("CSV"))//判断所要读取的扩展名
        //    {
        //        string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='text;HDR=NO;FMT=Delimited'";//有列的读取
        //        string commandText = "select * from [" + filename + "]";//SQL语句

        //        OleDbConnection olconn = new OleDbConnection(connStr);
        //        olconn.Open();
        //        OleDbDataAdapter odp = new OleDbDataAdapter(commandText, olconn);
        //        odp.Fill(dt);
        //        olconn.Close();
        //        odp.Dispose();
        //        olconn.Dispose();
        //    }
        //    return dt;
        //}

        private void openCSV(string filepach)
        {
            REngine engine = REngine.GetInstanceFromID("RDotNet") ?? REngine.CreateInstance("RDotNet");
            //bool isok = engine.IsRunning;
            string cmd = string.Format("dataset=read.csv('{0}')", filepach).Replace("\\", "\\\\");//不加Replace错误
            //string cmd = @"dataset=read.csv('C:\\Users\\wm\\Desktop\\煤与瓦斯2.csv')";//不加@错误
            string cmd2 = @"levels(dataset$突出规模)";

            engine.Evaluate(cmd);
            RDotNet.CharacterVector levels = engine.Evaluate(cmd2).AsCharacter();
            dataset = engine.Evaluate("dataset").AsDataFrame();

            for (int i = 0; i < dataset.ColumnCount; ++i)
            {
                dataGridView1.ColumnCount++;
                dataGridView1.Columns[i].Name = dataset.ColumnNames[i];
            }

            for (int i = 0; i < dataset.RowCount; ++i)
            {
                dataGridView1.RowCount++;
                dataGridView1.Rows[i].HeaderCell.Value = dataset.RowNames[i];

                for (int k = 0; k < dataset.ColumnCount; ++k)
                {
                    dataGridView1[k, i].Value = dataset[i, k];
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Gets the symbol names defined in this environment.
        /// </summary>
        /// <param name="all">Including special functions or not.</param>
        /// <returns>Symbol names.</returns>
        public string[] GetSymbolNames(bool all = false)
        {
            var symbolNames = new CharacterVector(Engine, this.GetFunction <R_lsInternal>()(handle, all));
            int length      = symbolNames.Length;
            var copy        = new string[length];

            symbolNames.CopyTo(copy, length);
            return(copy);
        }
Пример #3
0
        /// <summary> Sets the names of the vector.</summary>
        ///
        /// <exception cref="ArgumentException"> Incorrect length, not equal to vector length</exception>
        ///
        /// <param name="names"> A variable-length parameters list containing names.</param>
        public void SetNames(CharacterVector names)
        {
            if (names.Length != this.Length)
            {
                throw new ArgumentException("Names vector must be same length as list");
            }
            SymbolicExpression namesSymbol = Engine.GetPredefinedSymbol("R_NamesSymbol");

            SetAttribute(namesSymbol, names);
        }
Пример #4
0
        /// <summary>
        /// Executes the function. Match the function arguments by name.
        /// </summary>
        /// <param name="argNames">The names of the arguments. These can be empty strings for unnamed function arguments</param>
        /// <param name="args">The arguments passed to the function</param>
        /// <returns></returns>
        protected SymbolicExpression InvokeViaPairlist(string[] argNames, SymbolicExpression[] args)
        {
            var names     = new CharacterVector(Engine, argNames);
            var arguments = new GenericVector(Engine, args);

            arguments.SetNames(names);
            var argPairList = arguments.ToPairlist();

            //IntPtr newEnvironment = Engine.GetFunction<Rf_allocSExp>()(SymbolicExpressionType.Environment);
            //IntPtr result = Engine.GetFunction<Rf_applyClosure>()(Body.DangerousGetHandle(), handle,
            //                                                      argPairList.DangerousGetHandle(),
            //                                                      Environment.DangerousGetHandle(), newEnvironment);
            return(createCallAndEvaluate(argPairList.DangerousGetHandle()));
        }
Пример #5
0
        /// <summary> Sets the names of the vector. </summary>
        ///
        /// <param name="names"> A variable-length parameters list containing names.</param>
        public void SetNames(params string[] names)
        {
            CharacterVector cv = new CharacterVector(this.Engine, names);

            SetNames(cv);
        }
Пример #6
0
        static void Main(string[] args)
        {
            SetupPath(); // current process, soon to be deprecated

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

            engine.Initialize(); // required since v1.5

            // some random weight samples
            double[] weight = new double[] { 3.2, 3.6, 3.2, 1.7, 0.8, 2.9, 2, 1.4, 1.2, 2.1, 2.5, 3.9, 3.7, 2.4, 1.5, 0.9, 2.5, 1.7, 2.8, 2.1, 1.2 };
            double[] lenght = new double[] { 2, 3, 3.2, 4.7, 5.8, 3.9, 2, 8.4, 5.2, 4.1, 2.5, 3.9, 5, 2.4, 3.5, 0.9, 2.5, 2.7, 2.8, 2.1, 1.2 };

            // introduce the samples into R
            engine.SetSymbol("weight", engine.CreateNumericVector(weight));
            engine.SetSymbol("lenght", engine.CreateNumericVector(lenght));

            // set the weights and lenghts as a data frame (regular R syntax in string)
            engine.Evaluate("df <- data.frame(id=c(1:length(weight)), weight = weight,lenght = lenght )");


            // evaluate and retrieve mean
            double avg = engine.Evaluate("mean(df$weight)").AsNumeric().ToArray()[0];
            // same for standard deviation
            double std = engine.Evaluate("sd(df$weight)").AsNumeric().ToArray()[0];

            // NumericVector coeff = engine.Evaluate("coefficients(lm(df$weight ~ df$lenght ))").AsNumeric();
            // print output in console
            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-gb");

            //Show in console the weight and lenght data
            Console.WriteLine(string.Format("Weights: ({0})", string.Join(",",
                                                                          weight.Select(f => f.ToString(ci)) // LINQ expression
                                                                          )));
            Console.WriteLine(string.Format("Length: ({0})", string.Join(",",
                                                                         lenght.Select(f => f.ToString(ci)) // LINQ expression
                                                                         )));
            Console.WriteLine(string.Format("Sample size: {0}", weight.Length));
            Console.WriteLine(string.Format(ci, "Average: {0:0.00}", avg));
            Console.WriteLine(string.Format(ci, "Standard deviation: {0:0.00}", std));

            var result = engine.Evaluate("lm(df$weight ~ df$lenght)");

            engine.SetSymbol("result", result);
            var    coefficients = result.AsList()["coefficients"].AsNumeric().ToList();
            double r2           = engine.Evaluate("summary(result)").AsList()["r.squared"].AsNumeric().ToList()[0];
            double intercept    = coefficients[0];
            double slope        = coefficients[1];

            Console.WriteLine("Intercept:" + intercept.ToString());
            Console.WriteLine("slope:" + slope);
            Console.WriteLine("r2:" + r2);

            string fileName = "myplot.png";

            CharacterVector fileNameVector = engine.CreateCharacterVector(new[] { fileName });

            engine.SetSymbol("fileName", fileNameVector);

            engine.Evaluate("png(filename=fileName, width=6, height=6, units='in', res=100)");
            engine.Evaluate("reg <- lm(df$weight ~ df$lenght)");
            engine.Evaluate("plot(df$weight ~ df$lenght)");
            engine.Evaluate("abline(reg)");
            engine.Evaluate("dev.off()");
            //The file will save in debug directory

            Application.Run(new Form1());
            // After disposing of the engine, you cannot reinitialize nor reuse it
            engine.Dispose();
        }