最近在编心理学的实验程序,想借助R强大的统计功能进行后期的实验数据处理。经过大量的百度和谷歌之后成功实现在VBnet里引入R,于是想把经验和大家分享一下
准备:
1.R的程序包,
注意一定要是2.11版,版本太高,不支持在VBnet里面运行(R-2.11.1-win32.exe)。当然,版本太低也不行
下载地址是:
http://cran.r-project.org/bin/windows/base/old/2.11.1/R-2.11.1-win32.exe
2.R的COM库,下载的地址是:
http://ftp.ctex.org/mirrors/CRAN/contrib/extra/dcom/R_Scilab_DCOM3.0-1B5.exe
3.
最重要的一步,要下载一个rscproxy 的R包,很多人就是因为没有下载这个动态链接库(rscproxy.dll)而无法在VBnet(或C#)里调用(没有下载这个库会出现“异常来自 HRESULT:0x80040013”这样的错误提示)。下载地址是:
http://ftp.ctex.org/mirrors/CRAN/bin/windows/contrib/r-release/rscproxy_1.3-1.zip。
安装R,然后安装R的COM库,然后将rscproxy 包里面的rscproxy.dll复制到R的安装目录下的Bin文件夹下。
然后就可以(StatConnControls.ocx,StatConnectorClnt.dll和StatConnectorSrv.exe),见下图
然后,在模块里添加引用:
Imports STATCONNECTORCLNTLib
Imports StatConnectorCommonLib
Imports STATCONNECTORSRVLib
就可以调用函数了。
以下下是一个简单的启动示例(在module里)
Imports STATCONNECTORCLNTLib
Imports StatConnectorCommonLib
Imports STATCONNECTORSRVLib
Imports System.Runtime.InteropServices
Public Module StatRModule
Private RApp As StatConnector
Public Sub RInitialize()
''''''''''''''''''''''启动后台R''''''''''''''''''''''''''
Try
If RApp Is Nothing Then
RApp = New STATCONNECTORSRVLib.StatConnector()
End If
RApp.Init("R")
Catch exR As COMException
MsgBox("程序错误:" + exR.ToString, MsgBoxStyle.Critical, "错误")
RApp = Nothing
End Try
End Sub
Public Sub RTerminate()
''''''''''''''''''''''关闭后台R''''''''''''''''''''''''''
If RApp Is Nothing Then
Exit Sub
Else
RApp.Close()
RApp = Nothing
End If
End Sub
Public Function tDistBound(ByVal nSample As Integer, ByVal dSig As Double) As Double
RInitialize()
RApp.SetSymbol("nSample", nSample)
RApp.SetSymbol("dSig", dSig)
RApp.Evaluate("tDistBound<-qt(1-dSig/2, nSample - 2) * sqrt(nSample / (nSample - 1))")
tDistBound = CType(RApp.GetSymbol("tDistBound"), Double)
RTerminate()
End Function
C# 的引用可以参见以下文章
http://www.codeproject.com/KB/cs/RtoCSharp.aspx