C# R语言开发环境
R语言开发环境准备:
1:VS2012 和R语言安装包,我用的是R-3.3.0版本。注意在安装R语言时尽量将其安装在C盘同时安装路径中最好不要包含汉字。我的安装路径:"C:\Program Files\R\R-3.3.0。
2:在VS中新建工程。注意工程的.NET版本要在4.0以上。
R语言VS开发配置:
1:先在开发的工程中加入NuGet的R语言包,如下图操作:
点击红色区域,然后在弹出的页面中查找R.Net安装即可,如下图所示:
安装完成后即可进行开发设置。
2:在开发调用R语言时,程序需要指定R语言的Bin路径,具体代码如下:
public static void SetupPath()
{
var oldPath = System.Environment.GetEnvironmentVariable("PATH"); /////C:\Program Files\R\R-3.3.0\bin
var rPath = System.Environment.Is64BitProcess ? @"C:\Program Files\R\R-3.3.0\bin\x64" : @"C:\Program Files\R\R-3.3.0\bin\i386";
// Mac OS X
//var rPath = "/Library/Frameworks/R.framework/Libraries";
// Linux (in case of libR.so exists in the directory)
//var rPath = "/usr/lib";
if (Directory.Exists(rPath) == false)
throw new DirectoryNotFoundException(string.Format("Could not found the specified path to the directory containing R.dll: {0}", rPath));
var newPath = string.Format("{0}{1}{2}", rPath, System.IO.Path.PathSeparator, oldPath);
System.Environment.SetEnvironmentVariable("PATH", newPath);
// NOTE: you may need to set up R_HOME manually also on some machines
string rHome = "";
var platform = Environment.OSVersion.Platform;
switch (platform)
{
case PlatformID.Win32NT:
break; // R on Windows seems to have a way to deduce its R_HOME if its R.dll is in the PATH
case PlatformID.MacOSX:
rHome = "/Library/Frameworks/R.framework/Resources";
break;
case PlatformID.Unix:
rHome = "/usr/lib/R";
break;
default:
throw new NotSupportedException(platform.ToString());
}
if (!string.IsNullOrEmpty(rHome))
Environment.SetEnvironmentVariable("R_HOME", rHome);
}
注意图中加粗的程序代码,此处一定要写上你本地对应的R语言安装的Bin路径。
3:在设置完路径后可以调用开发了,其中可以调用R语言脚本,和函数,如下代码片段:
SetupPath(); //设置代码路径
using (REngine engine = REngine.GetInstance())
{
engine.Initialize(); // required since v1.5
/////////××××××此处为写小代码直接运行
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();
//////////××××××××结束
///××××××××直接进行调用脚本进行计算 engine.Evaluate("source('c:/testForR/test.R')");
string[] b = engine.Evaluate("source('c:/testForR/test2.R')").AsCharacter().ToArray();/////参数为脚本的存放地址
string str1 = "llq.p1<-"+b[0];
engine.Evaluate(str1);
string str2 = "print(llq.p1[4])";
string[] c = engine.Evaluate(str2).AsCharacter().ToArray();
/////×××××调用脚本结束
//// txtR.Text = c[0];
}
附录:
参考url 1:http://f.dataguru.cn/thread-229918-1-1.html
参考url2:http://www.yiibai.com/r/r_environment_setup.html
参考url3:http://rdotnet.codeplex.com/documentation
浙公网安备 33010602011771号