[英]What are the steps for calling a custom R routine (within a .R file) from a C# program?
using StatConnectorCommonLib;
using STATCONNECTORSRVLib;
StatConnector rConn = new StatConnector();
rConn.Init("R");
rConn.SetSymbol("n1", 5);
rConn.Evaluate("x1<-rnorm(n1)");
var o = rConn.GetSymbol("x1");
foreach (double d in o)
{
Response.Write(d + "<br />");
}
rConn.Close();
上面的代碼很好用,因為rnorm是內置的R函數。
我需要調用其他.R文件中編寫的其他自定義(用戶定義)函數。 例如samplefn(n)
我可能會搜索,但在Google上找不到它。
根據#hans-roggeman的建議,我嘗試了以下內容
rConn.Evaluate("source('C:\\Program Files (x86)\\R\\RFunctions\\samplefnRfile.R')");
以及這個。
rConn.Evaluate("source(\"C:\\Program Files (x86)\\R\\RFunctions\\samplefnRfile.R\")");
他們都給出相同的錯誤。 來自HRESULT的異常:0x80010105(RPC_E_SERVERFAULT)
您可以從C#獲取R文件
rConn.Evaluate("source('other_r_code.R')");
這將執行該文件中的代碼,因此請確保它具有函數定義並且沒有實際要執行的代碼。 您可以使用R中的setwd
和getwd
指定文件的完整路徑或使用工作目錄。
到目前為止,我所見過的R和OO語言的最佳集成是Dirk Eddelbuettel撰寫的Rcpp和RInside with C ++。
好的,我現在有了答案。 我不得不使用StatConnectorClass。
要使用此類,我必須打開StatConnectorsRVLib的屬性並將Embed Interop Types設置為False。
using StatConnectorCommonLib;
using STATCONNECTORSRVLib;
using STATCONNECTORCLNTLib;
StatConnectorClass rConn = new StatConnectorClass();
try
{
rConn.Init("R"); // here is where we initialize R
Response.Write("Initialized." + "<br />"); Response.Flush();
Response.Write("1" + "<br />"); Response.Flush();
string path = @"C:SOMEPATH\Black-Scholes.RData";
rConn.SetSymbol("path", path);
Response.Write("2" + "<br />"); Response.Flush();
rConn.Evaluate("load(path)");
Response.Write("3" + "<br />"); Response.Flush();
Int16 entry = 27;
rConn.SetSymbol("n1", entry);
Response.Write("6" + "<br />"); Response.Flush();
rConn.Evaluate("x1<-samplefn(n1)" );
Response.Write("Entered : " + entry.ToString() + "<br/> ");
Object o = rConn.GetSymbol("x1");
Response.Write("Ans:" + o.ToString() + "<br />"); Response.Flush();
rConn.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message );//+ " xx " + rConn.GetErrorText());
rConn.Close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.