1. Introduction
The photo is Suimono :) It includes Ebi Shinjyo, which is a steamed shrimp dumpling.In this article, I note how to execute R script files from C# and the execution results. I integrated C# and R with R.NET. R.NET has so simple APIs and is easy to use.
・R.NET
https://github.com/jmp75/rdotnetThe versions of .NET Framework, R.NET and R are as follows.
.NET Framework 4.5
R.NET 1.6.5
R 3.3.2
R.NET 1.6.5
R 3.3.2
2. Integrating C# and R
I want to use R to execute machine learning models, display useful charts and so on, and C# to process various parameters and pass them to R. It's because R has the good capabilities of graphical processing and machine learning but isn't good at handling objects.And I also want to incorporate R script files implemented by other persons such as quantitative analysts and data scientists, into C# applications.
2.1. C# Program
First, I note the C# program. It's required to pass arguments from it to a R script file and run the R script file. These are realized by the following methods. It's so simple :)
・ passing arguments from C# programs to R script files
The full source code is as follows :)
・ Program.cs
'C:/dev/R/test_data.csv' in this program is like the following csv file.
・ test_data.csv
・ passing arguments from C# programs to R script files
REngine.SetCommandLineArguments (string[] parameters)
・ running R script files
REngine.Evaluate ("source('script file path')")
The full source code is as follows :)
・ Program.cs
using RDotNet;
namespace FinancialEngineering
{
class Program
{
static void Main(string[] args)
{
var scriptFilePath = "C:/dev/R/test_script.R";
var riskCsvPath = "C:/dev/R/test_data.csv";
var valueAtRisk = "25750000000";
ExecuteScriptFile(scriptFilePath, riskCsvPath, valueAtRisk);
}
public static void ExecuteScriptFile(string scriptFilePath, string paramForScript1,
string paramForScript2)
{
using (var en = REngine.GetInstance())
{
var args_r = new string[2] { paramForScript1, paramForScript2 };
var execution = "source('" + scriptFilePath + "')";
en.SetCommandLineArguments(args_r);
en.Evaluate(execution);
}
}
}
}
namespace FinancialEngineering
{
class Program
{
static void Main(string[] args)
{
var scriptFilePath = "C:/dev/R/test_script.R";
var riskCsvPath = "C:/dev/R/test_data.csv";
var valueAtRisk = "25750000000";
ExecuteScriptFile(scriptFilePath, riskCsvPath, valueAtRisk);
}
public static void ExecuteScriptFile(string scriptFilePath, string paramForScript1,
string paramForScript2)
{
using (var en = REngine.GetInstance())
{
var args_r = new string[2] { paramForScript1, paramForScript2 };
var execution = "source('" + scriptFilePath + "')";
en.SetCommandLineArguments(args_r);
en.Evaluate(execution);
}
}
}
}
'C:/dev/R/test_data.csv' in this program is like the following csv file.
・ test_data.csv
date,risk_value
20160128,21261339422
20160129,22759109989
20160130,21405741891
...
20160128,21261339422
20160129,22759109989
20160130,21405741891
...
2.2. R Script File
Next, I wrote the following R script file. It's important that the arguments passed from the C# program become available by 'args <- commandArgs()'. These are stored after 'args[2]'.
・ test_script.R
・ test_script.R
args <- commandArgs()
riskValueFilepath <- args[2]
VaR <- args[3]
data <- read.csv(riskValueFilepath, header = TRUE)
attach(data)
x <- strptime(data$date, '%Y%m%d', tz = '')
par(xaxt = 'n')
plot(x, data$risk_value, type = 'n', xlab = '',ylab ='')
lines(x, data$risk_value, type = 'l',col = 'thistle4',add = T)
points(x, data$risk_value, type = 'p',pch = 20,col = ifelse(data$risk_value > VaR, 'tomato', 'thistle4'), add = T)
par(xaxt = 's')
y <- as.POSIXct(round(range(x), "days"))
axis.POSIXct(1,at = seq(y[1],y[2],by = "1 day"),format = '%Y%m%d')
title('Test of Integrating C# and R\n(Points above Value at Risk)', xlab = 'Date',ylab = 'Risk Value')
riskValueFilepath <- args[2]
VaR <- args[3]
data <- read.csv(riskValueFilepath, header = TRUE)
attach(data)
x <- strptime(data$date, '%Y%m%d', tz = '')
par(xaxt = 'n')
plot(x, data$risk_value, type = 'n', xlab = '',ylab ='')
lines(x, data$risk_value, type = 'l',col = 'thistle4',add = T)
points(x, data$risk_value, type = 'p',pch = 20,col = ifelse(data$risk_value > VaR, 'tomato', 'thistle4'), add = T)
par(xaxt = 's')
y <- as.POSIXct(round(range(x), "days"))
axis.POSIXct(1,at = seq(y[1],y[2],by = "1 day"),format = '%Y%m%d')
title('Test of Integrating C# and R\n(Points above Value at Risk)', xlab = 'Date',ylab = 'Risk Value')
3. Execution Result
The execution result is as follows. It noramlly ran :)
4. Conclusion
R.NET enables you to intagrate C# and R. Because passing arguments from C# to R and running R script files are possible, it's easy to incorporate R script files into C# applications.
Hello InuT,
ReplyDeleteThis is a very nice introduction articles. I duplicated the C# and R codes, the code seems work well. But I always run into an unhandled exception. The error messages like before while I run en.Evaluate(execution) in C#:
"An unhandled exception of type 'RDotNet.EvaluationException' occurred in RDotNet.dll
Additional information: Error in eval(expr, envir, enclos) : object 'p' not found"
I am wondering if you have a way to avoid this error.
Thanks.
Oliver
This comment has been removed by the author.
DeleteI also try it, but as soon as I include sources or libraries I get the same error, Oliver any work around?
DeleteDavid
Hello InuT,
ReplyDeleteHow can I make it work for user library ( additionally installed R packages)?
Does it work for outside base R?
How can I make it work for user library ( additionally installed R packages)?
DeleteYes the ones I tried are installed in R after installation, and also some of them where made by my as a Library with functions.
Does it work for outside base R? Whe I run the equivalent script direct in R it works Fine.
This comment has been removed by the author.
ReplyDeleteThank you for your guide to with upgrade information
ReplyDelete.NET Online Course
Thank you for your guide to with upgrade information
ReplyDelete.NET Online Course
Your post gave a clear idea about knowing the DevOps model and its importance
ReplyDeleteDot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery
perde modelleri
ReplyDeletesms onay
Vodafone Mobil Ödeme Bozdurma
NFTNASİLALİNİR.COM
ankara evden eve nakliyat
trafik sigortası
dedektör
https://kurma.website
aşk kitapları
smm panel
ReplyDeletesmm panel
is ilanlari blog
instagram takipçi satın al
HIRDAVATÇI BURADA
Https://www.beyazesyateknikservisi.com.tr
SERVİS
jeton hilesi indir