C#执行R文件的简单示例

首先下载RDotNet.dll、RDotNet.NativeLibrary.dll、Interop.STATCONNECTORCLNTLib.dll、Interop.StatConnectorCommonLib.dll及Interop.STATCONNECTORSRVLib.dll,引用如下名字空间:

using RDotNet;
using RDotNet.NativeLibrary;
using STATCONNECTORCLNTLib;
using StatConnectorCommonLib;
using STATCONNECTORSRVLib;
下面是基于Winform的示例代码,

public partial class FormCalculate : Form
    {
        public static REngine engine=null;
        public static int nRows = 50;
        DataTable data_old=null;
        //DataTable dt_view = null;
        public FormCalculate()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            ControlsHelper.SetDatagridViewDefaultStyle(dgvData);
        }

        private void FormImportData_Load(object sender, EventArgs e)
        {
            try
            {
                int width = int.Parse(System.Configuration.ConfigurationManager.AppSettings["数据处理页面的默认图片宽度"].ToString());
                splitContainer1.SplitterDistance =width;
                BackgroundWorker bw = new BackgroundWorker();
                bw.DoWork += BackgroundDeal;
                //bw.RunWorkerCompleted += RunCompleted;
                bw.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误提示:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            //Thread thread = new Thread(new ThreadStart(BackgroundDeal));
            //thread.Start();
           
            
        }
        private void BackgroundDeal(object sender, DoWorkEventArgs e)
        {//
            try
            {
                this.tslblMsg.Text = "正在初始化...";

                #region 初始化

                if (engine == null)
                {

                    string dllPath = System.Configuration.ConfigurationManager.AppSettings["R软件主程序目录"].ToString();
                    REngine.SetDllDirectory(dllPath);
                    REngine.CreateInstance("RDotNet");
                    engine = REngine.GetInstanceFromID("RDotNet");
                    engine.Initialize();
                    REngineExtension.CreateIsolatedEnvironment(engine);
                }
                #endregion

                #region 执行脚本
                this.tslblMsg.Text = "正在执行脚本语言...";
                string rscript = System.Configuration.ConfigurationManager.AppSettings["R脚本文件"].ToString();//R脚本
                //SymbolicExpression tt;
                engine.Evaluate(string.Format("source('{0}')", rscript));
                #endregion

                #region 显示数据
                this.tslblMsg.Text = "正在加载处理结果...";

                string fileName = System.Configuration.ConfigurationManager.AppSettings["R软件输出文件"].ToString();
                if (!File.Exists(fileName))
                {
                    MessageBox.Show("输出结果文件不存在!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                string extision = System.IO.Path.GetExtension(fileName);
                if (extision.ToLower().Equals(".csv"))//csv文件
                {
                    data_old = FileHelper.ImportFromCSV(fileName);
                }
                else//excel文件
                {
                    data_old = ExcelHelper.FastGetDataFromExcel(fileName);
                }
                string picName = System.Configuration.ConfigurationManager.AppSettings["R软件生成图片文件"].ToString();
                this.Invoke(new Action(delegate{
                    this.pictureBox1.Image = Image.FromFile(picName);
                    this.dgvData.DataSource = data_old;
                    //this.groupBox2.Text = string.Format("处理结果({0})", data_old.Rows.Count);
                    }));
                
                #endregion

                this.tslblMsg.Text = "";
            }
            catch (Exception ex)
            {
                this.tslblMsg.Text = ex.Message;
            }
        }
        private void RunCompleted(object sender,RunWorkerCompletedEventArgs e)
        {
            //this.tslblMsg.Text = "";
        }
        /// <summary>
        /// 开始处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                string rscript = System.Configuration.ConfigurationManager.AppSettings["R脚本文件"].ToString();//R脚本
                
                #region 测试区域
                //REngine.SetEnvironmentVariables();
                //REngine engine = REngine.CreateInstance("12321");
                //engine.Initialize();
                //object tt;
                //int n = 20;
                //StatConnector Sc1 = new StatConnector();
                //Sc1.Init("R");
                //Sc1.SetSymbol("n1", n);
                //Sc1.Evaluate("x1 <- n1");
                //tt = Sc1.GetSymbol("x1");
                //MessageBox.Show(tt.ToString());

                //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().ToString();
                //MessageBox.Show(a);
               // StatConnector Sc1 = new STATCONNECTORSRVLib.StatConnectorClass();
                SymbolicExpression tt;
                try
                {
                    //Sc1.Init("R");
                    //int n = 20;
                    //Sc1.SetSymbol("n1", n);
                    //Sc1.Evaluate("x1 <- n1");
                    //object tt1 = Sc1.GetSymbol("x1");
                    //MessageBox.Show(tt1.ToString());
                    //SymbolicExpression tt = engine.Evaluate("license()");//有返回值
                    tt = engine.Evaluate(string.Format("source('{0}')", rscript));
                    MessageBox.Show("计算完成");
                }
                catch (Exception ex)
                {
                    string error = string.Empty;
                    //error=Sc1.GetErrorId()+":"+Sc1.GetErrorText();
                    MessageBox.Show(ex.Message+"\n"+error);
                    //MessageBox.Show(Sc1.GetErrorId()+":"+Sc1.GetErrorText());
                    
                }
                
                
                #endregion

                //SymbolicExpression tt = engine.Evaluate("license()");//有返回值
                //SymbolicExpression tt= engine.Evaluate(string.Format("source('{0}')", rscript));
                //MessageBox.Show("计算完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行R脚本出错!\n错误提示:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
       
        /// <summary>
        /// 返回DataTable的前nRow行
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="nrow"></param>
        /// <returns></returns>
        private DataTable GetSubSetFromDataTable(DataTable dt,int nrow)
        {
            DataTable table = dt.Clone();
            for (int i = 0; i < Math.Min(dt.Rows.Count,nrow); i++)
            {
                DataRow row = table.NewRow();
                row.ItemArray = dt.Rows[i].ItemArray;
                table.Rows.Add(row);
            }
            return table;
        }
        /// <summary>
        /// 查看结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbtnRenew_Click(object sender, EventArgs e)
        {
            try
            {
                string fileName = System.Configuration.ConfigurationManager.AppSettings["R软件输出文件"].ToString();
                if (!File.Exists(fileName))
                {
                    MessageBox.Show("输出结果文件不存在!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                string extision = System.IO.Path.GetExtension(fileName);
                if (extision.ToLower().Equals(".csv"))//csv文件
                {
                    data_old = FileHelper.ImportFromCSV(fileName);
                }
                else//excel文件
                {
                    data_old = ExcelHelper.FastGetDataFromExcel(fileName);
                }
                this.dgvData.DataSource = data_old;
                //this.groupBox2.Text = string.Format("处理结果({0})", data_old.Rows.Count);
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误提示:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void dgvData_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
        {
            e.SortResult = (Convert.ToDouble(e.CellValue1) - Convert.ToDouble(e.CellValue2) > 0) ? 1 : (Convert.ToDouble(e.CellValue1) - Convert.ToDouble(e.CellValue2) < 0) ? -1 : 0;
        }

        
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数据之道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值