首先下载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;
}
}