码迷,mamicode.com
首页 > 编程语言 > 详细

C# 调用R语言

时间:2016-04-15 20:19:54      阅读:622      评论:0      收藏:0      [点我收藏+]

标签:

在.net项目中需要调用Matlab生成的DLL,但是在调用过程中报错,截图如下:

技术分享

在网上搜索一下资料,看到该博客:https://cn.mathworks.com/matlabcentral/newsreader/view_thread/282351

知道了我调用的DLL中有Matlab工具箱里面的函数,Matlab不允许某些工具箱中的工具被封装成DLL,于是就出现了上图所示的错误。

然后想用R语言实现。

1、先下载R软件:http://mirrors.opencas.cn/cran/,选择base

2、下载RDotNet并编译

   下载地址:http://rdotnet.codeplex.com/

   下载好后 打开 RDotNet.Tests解决方案,进行编译

3、测试

    新建一个工程,引用如下图:

技术分享

代码如下:

        private static void Main(string[] args)
        {
            string rHome = null;
            string rPath = null;
            if (args.Length > 0)
                rPath = args[0];
            if (args.Length > 1)
                rHome = args[1];
            Console.WriteLine(RDotNet.NativeLibrary.NativeUtility.FindRPaths(ref rPath, ref rHome));
            rHome = null;
            rPath = null;

            REngine.SetEnvironmentVariables(rPath: rPath, rHome: rHome);
            REngine e = REngine.GetInstance();
            //Console.WriteLine(RDotNet.NativeLibrary.NativeUtility.SetEnvironmentVariablesLog);
            // .NET Framework array to R vector.
            NumericVector group1 = e.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 });
            e.SetSymbol("group1", group1);
            // Direct parsing from R script.
            NumericVector group2 = e.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 = e.Evaluate("t.test(group1, group2)").AsList();
            double p = testResult["p.value"].AsNumeric().ToArray()[0];

            Console.WriteLine("Group1: [{0}]", string.Join(", ", group1));
            Console.WriteLine("Group2: [{0}]", string.Join(", ", group2));
            Console.WriteLine("P-value = {0:0.000}", string.Join(", ", p));

            e.Dispose();
        }

程序会根据R软件的注册表找到对应的dll从而实现调用R语言。

在调用R语言的时候,如果有的程序包没有引用的话需要在R程序菜单下的 “程序包” 来安装对应功能的程序包。

解决问题参考的博客:

https://psychwire.wordpress.com/2011/06/19/making-guis-using-c-and-r-with-the-help-of-r-net/

https://psychwire.wordpress.com/2011/06/19/making-guis-using-c-and-r-with-the-help-of-r-net/

http://blog.csdn.net/guoer9973/article/details/45953471

 

C# 调用R语言

标签:

原文地址:http://www.cnblogs.com/GIScore/p/5396647.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!