c# - Using R in asp.net web application -
i trying use r script in asp.net c# web application. trying use simple r script concatenate 2 strings single one.
below cs code
using rdotnet; using system; using system.collections.generic; using system.io; using system.linq; using system.web; using system.web.ui; using system.web.ui.webcontrols; public partial class _default : system.web.ui.page { protected void page_load(object sender, eventargs e) { } private static double evaluateexpression(rengine engine, string expression) { var expressionvector = engine.createcharactervector(new[] { expression }); engine.setsymbol("expr", expressionvector); // wrong -- need parse expression before evaluation //var result = engine.evaluate("eval(expr)"); // right way this!!! var result = engine.evaluate("eval(parse(text=expr))"); var ret = result.asnumeric().first(); return ret; } public static void setuppath(string rversion = "r-3.2.1") { var oldpath = system.environment.getenvironmentvariable("path"); var rpath = system.environment.is64bitprocess ? string.format(@"c:\program files\r\{0}\bin\x64", rversion) : string.format(@"c:\program files\r\{0}\bin\i386", rversion); if (!directory.exists(rpath)) throw new directorynotfoundexception( string.format(" r.dll not found in : {0}", rpath)); var newpath = string.format("{0}{1}{2}", rpath, system.io.path.pathseparator, oldpath); system.environment.setenvironmentvariable("path", newpath); } protected void button1_click(object sender, eventargs e) { setuppath(); rengine.setenvironmentvariables(); rengine engine = rengine.getinstance(); // rengine requires explicit initialization. // can set parameters. engine.initialize(); //engine.evaluate("g<-5+3+2"); engine.evaluate("g<-paste('hello r', 'test')"); label1.text = evaluateexpression(engine, "g").tostring(); } }
i have click button , when click want output showed in web page.
when run code , click button getting text
nan
in label control page. when run
engine.evaluate("g<-5+3+2");
instead of
engine.evaluate("g<-paste('hello r', 'test')");
i getting correct value 10 in label of page. not aware of error , dont know how output in web page. tried in websites code has been written console applications , nothing asp.net web application.
can me problem solved displaying r output in web page?
you don't need evaluateexpression
@ all. use engine.getsymbol("g")
instead.
the nan output happens because of asnumeric()
conversion inside evaluateexpression
. work numeric output, not character.
here's minimal example numeric , character variables:
static void main(string[] args) { rengine.setenvironmentvariables(); rengine engine = rengine.getinstance(); engine.initialize(); engine.evaluate("x <- 40 + 2"); engine.evaluate("s <- paste('hello', letters[5])"); var x = engine.getsymbol("x").asnumeric().first(); var s = engine.getsymbol("s").ascharacter().first(); console.writeline(x); console.writeline(s); }
Comments
Post a Comment