Skip to main content
 首页 » 编程设计

c#之R 引擎未初始化

2024年02月13日16qlqwjy

static void Main(string[] args) 
{ 
    // Set the folder in which R.dll locates. 
    var envPath = Environment.GetEnvironmentVariable("PATH"); 
    var rBinPath = @"C:\R-3.0.2\bin\i386\"; 
    Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + rBinPath); 
    using (REngine engine = REngine.CreateInstance("RDotNet")) 
    { 
        // Initializes settings. 
        engine.Initialize(); // After Executing this line its crashing. 
 
        NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 }); 
        engine.SetSymbol("group1", group1); 
        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.ReadLine(); 
    } 

嗨 当我执行上面的代码时,它在初始化时崩溃了。 操作系统是 Windows XP sp3(32 位) R 版本- R-3.0.2 使用 R.Net(1.5 版本)

请帮助我从 C# 连接到 R

请您参考如下方法:

我认为引擎崩溃是因为你有一些 R 路径错误。最好从 Windows 注册表中读取路径。

尝试这样的事情:

using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\R-core\R")){ 
    var envPath = Environment.GetEnvironmentVariable("PATH"); 
    string rBinPath = (string)registryKey.GetValue("InstallPath"); 
    string rVersion = (string)registryKey.GetValue("Current Version"); 
    rBinPath = System.Environment.Is64BitProcess ? rBinPath + "\\bin\\x64" :  
                                                     rBinPath + "\\bin\\i386"; 
    Environment.SetEnvironmentVariable("PATH",  
                          envPath + Path.PathSeparator + rBinPath); 
} 
using (REngine engine = REngine.CreateInstance("RDotNet")){ 
              // same code here  
} 

当然你应该添加正确的引用:

using Microsoft.Win32; 
using RDotNet; 
using System.IO;