Background Color:
 
Background Pattern:
Reset
Thursday, November 23, 2017
menu click
Search

R Class

using System;
using STATCONNECTORSRVLib;
using System.Collections;
using System.IO;

namespace RNET
{
public class R
{
private StatConnectorClass _statCon;
private RCharDev _characterDevice;

public static bool Designtime
{
get
{
try
{
//return (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv");
return false;
}
catch { }
return false;
}
}

private int _dbglvl = 0;
private string _logfile = "";
private void log(int lvl, string msg)
{
if (lvl <= _dbglvl)
{
StreamWriter w = File.AppendText(_logfile);
w.WriteLine(
"{0} {1} {2}", DateTime.Now.ToString("u"), lvl, msg);
w.Flush();
w.Close();
}
}

public R()
{
_statCon =
new StatConnectorClass();
_statCon.Init(
"R");
_characterDevice =
new RCharDev();
SetCharacterOutputDevice(_characterDevice);
}

public R(int dbglvl, string dbgfile):this()
{
_dbglvl = dbglvl;
_logfile = dbgfile;
}

public RCharDev Output { get { return _characterDevice; } }

public void loadLibrary(string lib)
{
string cmdSurvLib = "library('" + lib + "')";
EvaluateNoReturn(cmdSurvLib);
}

public object Evaluate(string cmd)
{
try
{
//ifelse(is.null(Description$test),"",Description$test)
//if(is.null(names(Data))) "NULL" else names(Data)
log(5, "Evaluate:" + cmd);
cmd =
"if(is.null(" + cmd + ")) \"NULL\" else " + cmd ;
object res= _statCon.Evaluate(cmd);
if (res.ToString() == "NULL")
{
return null;
}
else
{
return res;
}
}
catch (Exception exc)
{
string statErr = "";
try
{
statErr = GetErrorText();
}
catch { }
string Rerror = GetErrMessage();
log(1,
"Evaluate Exception for cmd: " + cmd);
log(1,
"Exception: " + exc.Message);
log(1,
"statConError: " + statErr);
log(1,
"R error: " + Rerror);
Exception detEx= new Exception("Could not evaluate : " + cmd + " : " + exc.Message + " statConError:" + statErr, exc);
throw new Exception("Could not evaluate : " + cmd + " : " + Rerror);
}
}

private string GetErrMessage()
{
string err = "";
try
{
object o = Evaluate("geterrmessage()");
err = (
string)o;
}
catch { }
return err;
}
 
public void EvaluateNoReturn(string cmd)
{
try
{
log(5,
"EvaluateNoReturn:" + cmd);
_statCon.EvaluateNoReturn(cmd);
}
catch (Exception exc)
{
string statErr="";
try
{
statErr = GetErrorText();
}
catch { }
string Rerror = GetErrMessage();
log(1,
"EvaluateNoReturn Exception for cmd: " + cmd);
log(1,
"Exception: " + exc.Message);
log(1,
"statConError: " + statErr);
log(1,
"R error: " + Rerror);
Exception detEx = new Exception("Could not evaluate : " + cmd + " : " + exc.Message + " statConError:" + statErr, exc);
throw new Exception("Could not evaluate : " + cmd + " : " + Rerror);
}
}

public void SetCharacterOutputDevice(RCharDev output)
{
_statCon.SetCharacterOutputDevice(output);
}
public string GetErrorText() { return _statCon.GetErrorText(); }
private string name;
public string Name
{
get { return name; }
set { name = value; }
}

public string[] DataVariables
{
get
{
string cmdVars = "names(Data)";
object result = Evaluate(cmdVars);
return ((string[])result);
}
}

public RVar Data
{
get { return (getVar("Data")); }
}

public string evaluateAsText(string cmd)
{
string cmdprint = cmd.StartsWith("print") ? cmd : "print(" + cmd + ")";
Output.Clear();
try
{
EvaluateNoReturn(cmdprint);
}
catch { }
string txt = Output.Text;
if (txt.ToLower().IndexOf("error") >= 0)
{
throw new Exception("evaluateAsTextException:" + txt);
}
Output.Clear();
return txt;
}

public string evaluateAsHtml(string cmd)
{
string cmdlib = "library(xtable)";
string cmdHtml = "print(xtable(as.data.frame(" + cmd + ")[1:10,]),type=\"html\")";
Evaluate(cmdlib);
string html = evaluateAsText(cmdHtml);
if (html.ToLower().IndexOf("<table") > 0 && html.ToLower().IndexOf("</table>") < 0)
{
html = html.Substring(0, html.ToLower().LastIndexOf(
"</tr>") + 5) + "\n";
}
html = html.Substring(0, html.ToLower().LastIndexOf(
"</table>") - 1) + "\n";
html +=
"<TR><TD colspan=3>.... result continues, only first 10 rows shown ... </TD></TR></table>\n";
return html;
}

public void clear()
{
string cmdClear = "rm(list=objects())";
EvaluateNoReturn(cmdClear);
}

public Array getVariableValues(string var)
{
if (!hasVar("DataLabels$" + var))
{
createDataLabels();
}
object o = null;
string cmd = "DataLabels$" + var + "[,1]";
o = Evaluate(cmd);
return (Array)o;
}

public string[] getVariableValueLabels(string var)
{
if (!hasVar("DataLabels$" + var))
{
createDataLabels();
}
object o = null;
string cmd = "DataLabels$" + var + "[,2]";
o = Evaluate(cmd);
return (string[])o;
}

public string getVariableValueLabelValue(string var, string val)
{
if (!hasVar("DataLabels$" + var))
{
createDataLabels();
}
//DataLabels$PMNX50[DataLabels$PMNX50[,1]=="-30",2]
object o = null;
string cmd = "DataLabels$" + var + "[DataLabels$"+var+"[,1]==\""+val+"\",2]";
o = Evaluate(cmd);
return (string)o;
}

public string[] getVariableValuesDefault(string var)
{
int len = (int)Evaluate("length(levels(as.factor(Data$" + var + ")))");
if (len == 0){
return null;
}
else if (len == 1)
{
string[] res = new string[1];
res[0]=(
string)Evaluate("levels(as.factor(Data$" + var + "))");
return res;
}
else if (len < 8)
{
return (string[])Evaluate("levels(as.factor(Data$" + var + "))");
}
else
{
Array vals = (Array)Evaluate("summary(Data$" + var + ")");
string[] strvals = new string[vals.Length];
for (int i = 0; i < vals.Length; i++)
{
strvals[i] = vals.GetValue(i).ToString();
}
return strvals;
}
}

public string[] getVariableValueLabelsDefault(string var)
{
int len = (int)Evaluate("length(levels(as.factor(Data$" + var + ")))");
if (len == 0){
return null;
}
else if (len == 1)
{
string[] res = new string[1];
res[0] = (
string)Evaluate("levels(as.factor(Data$" + var + "))");
return res;
}
else if (len < 8)
{
return (string[])Evaluate("levels(as.factor(Data$" + var + "))");
}
else
{
return (string[])Evaluate("paste(names(summary(Data$" + var + ")),summary(Data$" + var + "),sep=':')");
}
}

public void createDataLabels()
{
foreach (string var in DataVariables)
{
if (!hasVar("DataLabels$" + var))
{
string[] vals = getVariableValuesDefault(var);
string[] labs = getVariableValueLabelsDefault(var);
setDataLabels(var, vals, labs);
}
}
}

public void setDataLabels(string var, string[] val, string[] lab)
{
string cmd;
if (!hasVar("DataLabels"))
{
cmd =
"DataLabels<-list()";
EvaluateNoReturn(cmd);
}
if (val == null)
{
cmd =
"DataLabels$" + var + "<-matrix(c(NA,NA),ncol=2)";
}
else
{
for (int i = 0; i < val.Length; i++)
{
val[i] = val[i].Replace(
@"\", @"\\");
val[i] = val[i].Replace(
@"'", @"\'");
}
for (int i = 0; i < val.Length; i++)
{
lab[i] = lab[i].Replace(
@"\", @"\\");
lab[i] = lab[i].Replace(
@"'", @"\'");
}
string vals = "'" + string.Join("','", val) + "'";
string labs = "'" + string.Join("','", lab) + "'";
cmd =
"DataLabels$" + var + "<-matrix(c(" + vals + "," + labs + "),ncol=2)";
}
EvaluateNoReturn(cmd);
}

public void createDescription()
{
string cmd = "Description<-list()";
EvaluateNoReturn(cmd);
string[] items = new string[] { "xlabel", "ylabel", "grid", "bold", "title", "source", "margins", "showtitle", "showsource" };
foreach (string item in items)
{
cmd =
"Description$"+item+"<-\"\"";
EvaluateNoReturn(cmd);
}
cmd =
"Description$info<-list()";
EvaluateNoReturn(cmd);
}

public void setDescription(string var, string val)
{
if (!hasVar("Description"))
{
createDescription();
}
string[] spl=var.Split('$');
for (int i = 1; i < (spl.Length - 1); i++)
{
string vr = "Description$" + string.Join("$", spl, 0, i);
if (!hasVar(vr))
{
string cmdv = vr + "<-list()";
EvaluateNoReturn(cmdv);
}
}
string cmd;
if (val == null)
{
cmd =
"Description$" + var + "<-NULL";
}
else
{
cmd =
"Description$" + var + "<-\"" + val + "\"";
}
EvaluateNoReturn(cmd);
}

public string getDescription(string var)
{
if(!hasVar("Description")){
return null;
}
string cmd = "Description$" + var;
object o = null;
try
{
o = Evaluate(cmd);
}
catch {
}
return (o == null) ? null : o.ToString();
}

public string[] InfoItems
{
get
{
if (!hasVar("Description"))
{
return null;
}
string cmd = "names(Description$info)";
object o = null;
try
{
o = Evaluate(cmd);
}
catch { }
if (o == null)
{
return null;
}
else if (o is string)
{
return new string[] { o.ToString() };
}
else
{
return (string[])o;
}
}
}

public string getInfo(string var)
{
if (var.IndexOf('$') >= 0)
{
throw new Exception("Illegal character in name");
}
return getDescription("info$" + var);
}

public void setInfo(string var, string val)
{
setDescription(
"info$" + var, val);
}

public void removeInfo(string var)
{
setDescription(
"info$" + var, null);
}
public string getDescription()
{
string cmd = "Description";
return evaluateAsText(cmd);
}

public string DataStructure
{
get
{
string cmd = "str(Data)";
return evaluateAsText(cmd);
}
}

public string getDataStructure(string var)
{
string cmd = "str(Data$" + var + ")";
return evaluateAsText(cmd);
}
public string getDataType(string var)
{
string cmd = "typeof(Data$" + var + ")";
object o = Evaluate(cmd);
return (string)o;
}

public string getDataCardinality(string var)
{
string cmd = "is.ordered(Data$" + var + ")";
object o = Evaluate(cmd);
if ((bool)o) return "Ordered";
cmd =
"is.factor(Data$" + var + ")";
o = Evaluate(cmd);
if ((bool)o) return "Factor";
return "Numeric";
}

public void setDataVarLabel(string var, string lab, string nwlab)
{
string card = getDataCardinality(var);
string oper = getOper(card);
string[] levels = getDataLevels(var);
string strlevels = "\"" + string.Join("\",\"", levels) + "\"";
string strnwlevels = strlevels.Replace("\"" + lab + "\"", "\"" + nwlab + "\"");
string cmd = "Data$" + var + "<-"
+ oper + "("
+ "Data$" + var
+
", labels=c(" + strnwlevels + ")"
+ ")";
EvaluateNoReturn(cmd);
}
private string getOper(string type)
{
switch (type.ToLower())
{
case "ordered":
return "ordered";
case "factor":
return "factor";
case "numeric":
return "as.numeric";
case "double":
return "as.double";
case "integer":
return "as.integer";
case "character":
return "as.character";
case "date":
return "as.date";
default:
throw new Exception("unknown type: " + type);
}
}

public void setDataCardinality(string var, string cardinality)
{
string oper = getOper(cardinality);
string cmd =
"Data$" + var + "<-"
+ oper + "("
+ "Data$" + var
+
")";
EvaluateNoReturn(cmd);
}
public void setDataType(string var, string type)
{
string oper = getOper(type);
string cmd =
"Data$" + var + "<-"
+ oper + "("
+ "Data$" + var
+
")";
EvaluateNoReturn(cmd);
}
 
public string[] getDataLevels(string var)
{
string cmd = "levels(as.factor(Data$" + var + "))";
object o = Evaluate(cmd);
if (o == null)
{
return null;
}
else if (o is string)
{
string[] res = new string[1];
res[0] = (
string)o;
return res;
}
else
{
return (string[])o;
}
}
public void removeData()
{
string cmd = @"rm(Data)";
EvaluateNoReturn(cmd);
}

public void readData(string datafile)
{
try
{
string ext = Path.GetExtension(datafile).Trim(new char[] { '.' }).ToLower();
string cmdRead = "";
switch (ext)
{
case "sav":
string cmdLib = "library(foreign)";
cmdRead =
@"Data <- read.spss('" + datafile.Replace("\\", "/") + "',to.data.frame = TRUE)";
EvaluateNoReturn(cmdLib);
EvaluateNoReturn(cmdRead);
break;
case "tab": //case "txt":
cmdRead = @"Data <- read.table('" + datafile.Replace("\\", "/") + "',quote = \"\", sep = \"\\t\" ,header=T)";
EvaluateNoReturn(cmdRead);
break;
default: //case "txt":
cmdRead = @"Data <- read.table('" + datafile.Replace("\\", "/") + "',header=T)";
EvaluateNoReturn(cmdRead);
break;
}
}
catch (Exception exc)
{
throw new Exception("Could not read data, possibly errors in data format: " + exc.Message, exc);
}
}

public void load(string filename)
{
try
{
clear();
string cmdLoad = "load(\"" + filename.Replace("\\", "/") + "\")";
EvaluateNoReturn(cmdLoad);
}
catch (Exception exc)
{
throw exc;
}
}

public void loadData(string tempPath, string data)
{
string path = null;
try
{
clear();
string guid = Guid.NewGuid().ToString();
path = tempPath +
Path.DirectorySeparatorChar + guid + ".txt";
StreamWriter sr = File.CreateText(path);
sr.WriteLine(data);
sr.Close();
readData(path);
}
catch (Exception exc)
{
try
{
File.Delete(path);
}
catch { }
throw exc;
}
}

public void save(string saveasname)
{
try
{
string cmdSave = "save(list=objects(),file=\"" + saveasname.Replace("\\", "/") + "\")";
EvaluateNoReturn(cmdSave);
}
catch (Exception exc)
{
throw exc;
}
}

public bool hasVar(string varname)
{
try
{
if (varname.IndexOf('$') < 0)
{
string cmd = "length(ls()[ls()==\"" + varname + "\"])==1";
object val = Evaluate(cmd);
return (bool)val;
}
else
{
string basevar = varname.Split('$')[0];
string cmd = "length(ls()[ls()==\"" + basevar + "\"])==1";
object val = Evaluate(cmd);
bool res=(bool)val;
if (!res)
{
return false;
}
else
{
val = Evaluate(varname);
return val != null;
}
}
}
catch { }
return false;
}

public RVar getVar(string varname)
{
RVar rvar = new RVar(this, varname);
try
{
string cmdSummary = "summary(" + varname + ")";
rvar.Summary = evaluateAsText(cmdSummary);
}
catch { }
return rvar;
}

public static bool isNumber(string val)
{
for (int i = 0; i < val.Length; i++)
{
if ((val[i] > '9' || val[i] < '0') && val[i] != '-' && val[i] != '.' && val[i] != ',')
{
return false;
}
}
return true;
}
}
}