本文整理匯總了C#中RDotNet.REngine.Evaluate方法的典型用法代碼示例。如果您正苦於以下問題:C# REngine.Evaluate方法的具體用法?C# REngine.Evaluate怎麽用?C# REngine.Evaluate使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類RDotNet.REngine
的用法示例。
在下文中一共展示了REngine.Evaluate方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: DoTest
private static void DoTest(REngine engine)
{
var setupStr = @"library(deldir)
set.seed(421)
x <- runif(20)
y <- runif(20)
z <- deldir(x,y)
w <- tile.list(z)
z <- deldir(x,y,rw=c(0,1,0,1))
w <- tile.list(z)
z <- deldir(x,y,rw=c(0,1,0,1),dpl=list(ndx=2,ndy=2))
w <- tile.list(z)
";
engine.Evaluate(setupStr);
var res = new List<List<Tuple<double, double>>>();
var n = engine.Evaluate("length(w)").AsInteger()[0];
for (int i = 1; i <= n; i++)
{
var x = engine.Evaluate("w[[" + i + "]]$x").AsNumeric().ToArray();
var y = engine.Evaluate("w[[" + i + "]]$y").AsNumeric().ToArray();
var t = x.Zip(y, (first, second) => Tuple.Create(first, second)).ToList();
res.Add(t);
}
}
示例2: TestPendingFinalizersThreadingIssues
private static void TestPendingFinalizersThreadingIssues(REngine e)
{
e.Evaluate("f <- function(a) {if (length(a)!= 1) stop('What goes on?')}");
var f = e.Evaluate("f").AsFunction();
try
{
e.Evaluate("f(letters[1:3])");
}
catch (EvaluationException)
{
}
f.Invoke(e.CreateCharacterVector(new[] { "blah" }));
try
{
f.Invoke(e.CreateCharacterVector(new[] { "blah", "blah" }));
}
catch (EvaluationException)
{
Console.WriteLine("Caught the expected exception");
}
f = null;
GC.Collect();
GC.WaitForPendingFinalizers();
e.Dispose();
Console.WriteLine("Just waiting for crash...");
GC.Collect();
GC.WaitForPendingFinalizers();
}
示例3: rdotnet_discussions_646729
static void rdotnet_discussions_646729(REngine engine)
{
var setup = @"library(rdotnetsamples)
rdotnetsamples::register_default_progress_handler()
";
engine.Evaluate(setup);
var myRFunction = @"
my_r_calculation <- function()
{
for (i in seq(0, 100, by=20)) {
rdotnetsamples::broadcast_progress_update(paste0('Some Update Message for ', i), i);
}
}
";
engine.Evaluate(myRFunction);
engine.Evaluate("my_r_calculation()");
var unixDllPath = engine.Evaluate("getLoadedDLLs()$rdotnetsamples[['path']]").AsCharacter()[0];
var dllPath = unixDllPath.Replace("/", "\\");
var dll = new DynamicInterop.UnmanagedDll(dllPath);
TestCallback cback = new TestCallback();
CallBackHandlers cbh = new CallBackHandlers();
cback.MyHandler = cbh.ProcessProgress;
string cFunctionRegisterCallback = "register_progress_handler";
register_default_progress_handler registerHandlerFun = dll.GetFunction<register_default_progress_handler>(cFunctionRegisterCallback);
registerHandlerFun(cback.MyHandler);
Console.WriteLine();
Console.WriteLine("After registering the callback with a function pointer to a C# function:");
Console.WriteLine();
engine.Evaluate("my_r_calculation()");
}
示例4: ReproIssue169
private static void ReproIssue169(REngine engine)
{
engine.Evaluate("library(mirt)");
engine.Evaluate("x=mirt(Science,1)");
S4Object obj111 = engine.GetSymbol("x").AsS4();
engine.Evaluate("ff=fscores(x, response.pattern=c(1,0,0,0))");
GenericVector dataset111 = engine.GetSymbol("ff").AsList();
NumericVector v = dataset111[0].AsNumeric();
double firstval = v[0];
}
示例5: calcSDev
static double calcSDev (REngine engine, double[] arr)
{
// Note: only one quick and slightly dirty way to do it
NumericVector rVector = engine.CreateNumericVector(arr);
engine.SetSymbol ("x", rVector);
return engine.Evaluate ("sd(x)").AsNumeric () [0];
}
示例6: TestOptimCsharp
static void TestOptimCsharp(REngine engine)
{
var rand = new Random(0);
int n = 10000;
double x, y, r, xb, yb, rb;
rb = double.MaxValue; xb = yb = double.MaxValue;
engine.Evaluate("rosen <- function(x, y) { (1-x)**2 + 100*(y-x*x)**2 }");
Console.WriteLine("*** Try a basic way to call the function in R ***");
for (int i = 0; i < n; i++)
{
x = -1 + rand.NextDouble() * (3 - (-1));
y = -1 + rand.NextDouble() * (3 - (-1));
r = engine.Evaluate(string.Format("rosen({0}, {1})", x, y)).AsNumeric().ToArray()[0];
if (r < rb)
{
rb = r;
xb = x;
yb = y;
}
}
Console.WriteLine("The best score r={0} is for x={1}, y={2}", rb, xb, yb);
Console.WriteLine("*** Try an R function 'pointer' with a vectorized function call. Faster, if you can do it this way***");
var f = engine.GetSymbol("rosen").AsFunction();
double[] xa = new double[n], ya = new double[n];
rand = new Random(0);
for (int i = 0; i < n; i++)
{
xa[i] = -1 + rand.NextDouble() * (3 - (-1));
ya[i] = -1 + rand.NextDouble() * (3 - (-1));
}
double[] ra = f.Invoke(new[] { engine.CreateNumericVector(xa), engine.CreateNumericVector(ya) })
.AsNumeric().ToArray();
rb = ra.Min();
int indBest = -1;
for (int i = 0; i < ra.Length; i++)
{ // no which.min in C#. Should call R here too...
if (ra[i] <= rb)
indBest = i;
}
Console.WriteLine("The best score r={0} is for x={1}, y={2}", rb, xa[indBest], ya[indBest]);
}
示例7: GenetateLatencyVsMessageLengthPlot_RScript
static void GenetateLatencyVsMessageLengthPlot_RScript(REngine engine, string latencyCsvFilename)
{
//For formatting purposes, make sure the filename is acceptable for R function read.csv
string fileToReadFromCommand = latencyCsvFilename.Replace(@"\", @"/");
//Convert to R character vector
CharacterVector cvFilename = engine.CreateCharacterVector(new[] { fileToReadFromCommand });
// and assign it to variable (in R engine) called fileToReadFrom
engine.SetSymbol("fileToReadFrom", cvFilename);
//And then evaluate the script - this uses the 'fileToReadFrom' in a read.csv call
engine.Evaluate(MyRDotNetApplication.Properties.Resources.latencyVsMessageLengthScatterPlot); //R-Script to generate plot
}
示例8: TestCallStop
private static void TestCallStop(REngine engine)
{
try
{
engine.Evaluate("stop('Just stop')");
}
catch (Exception ex)
{
counter++;
Console.WriteLine(string.Format("Caught an exception ({0})", counter));
Console.WriteLine(ex.ToString());
}
Console.WriteLine("Recovered from evaluation exception?");
}
示例9: stackoverflow_27597542_2752565
/// <summary>
/// http://stackoverflow.com/q/27597542/2752565
/// </summary>
static void stackoverflow_27597542_2752565 (REngine engine)
{
var createModel = @"
set.seed(0)
x <- ts(rnorm(100))
library(forecast)
blah <- ets(x)
# str(blah)
";
engine.Evaluate (createModel);
var m = engine.GetSymbol ("blah").AsList ();
var components = m ["components"].AsCharacter ().ToArray ();
for (int i = 0; i < components.Length; i++) {
Console.WriteLine ("m$components[{0}] = {1}", i + 1, components [i]);
}
}
示例10: UserReported
private static DataFrame UserReported(REngine engine)
{
// Incomplete data and repro info.
// See https://rdotnet.codeplex.com/discussions/569196
NumericVector PreprocessedValue = null;
DataFrame PredictedData = null;
// Some info was missing. Make up.
string StartDate = "2001-01-01";
double[] PreProcessedList = new[] { 1.1, 7.3, 4.5, 7.4, 11.23, 985.44 };
string days = "2"; string interval = "3";
PreprocessedValue = engine.CreateNumericVector(PreProcessedList);
// Assign the Utilization value to R variable UtilValue
engine.SetSymbol("PreprocessedValue", PreprocessedValue);
engine.Evaluate("library(forecast)");
engine.Evaluate("StartDate <- as.Date('" + StartDate + "') + " + days);
engine.Evaluate("size = length(seq(from=as.Date('" + StartDate + "'), by='" + "day" + "', to=as.Date(StartDate)))");
engine.Evaluate("startDate <- as.POSIXct('" + StartDate + "')");
engine.Evaluate("endDate <- StartDate + as.difftime(size, units='" + "days" + "')");
engine.Evaluate("PredictDate = seq(from=StartDate, by=" + interval + "*60, to=endDate)");
engine.Evaluate("freq <- ts(PreprocessedValue, frequency = 20)");
engine.Evaluate("forecastnavie <-snaive(freq, Datapoints)");
engine.Evaluate("PredictValue = (forecastnavie$mean)");
engine.Evaluate("PredictedData = cbind(PredictValue, data.frame(PredictDate))");
PredictedData = engine.Evaluate("PredictedData").AsDataFrame();
return PredictedData;
}
示例11: TestMultiThreads
private static void TestMultiThreads(REngine engine)
{
engine.Evaluate("x <- rnorm(10000)");
var blah = engine.GetSymbol("x").AsNumeric().ToArray();
double[][] res = new double[2][];
// Can two threads access in parallel the same
Parallel.For(0, 2, i => readNumericX(i, res, engine));
engine.Evaluate("x <- list()");
engine.Evaluate("x[[1]] <- rnorm(10000)");
engine.Evaluate("x[[2]] <- rnorm(10000)");
// Can two threads access in parallel the same list
// Usually bombs, though passes sometimes.
// The console output would report the following:
//Error: unprotect_ptr: pointer not found
//Error: R_Reprotect: only 3 protected items, can't reprotect index 9
//Error: unprotect_ptr: pointer not found
//Parallel.For(0, 2, i => readNumericList(i, res, engine));
// And in seqence, but from other threads - seems to work consistently
Parallel.For(0, 1, i => readNumericList(i, res, engine));
Parallel.For(1, 2, i => readNumericList(i, res, engine));
Console.WriteLine(res[1][1]);
}
示例12: ReproWorkitem43
private static void ReproWorkitem43(REngine engine)
{
Random r = new Random(0);
int N = 500;
int n1 = 207;
int n2 = 623;
var arGroup1Intensities = new double[N][];
var arGroup2Intensities = new double[N][];
for (int i = 0; i < N; i++)
{
arGroup1Intensities[i] = new double[n1];
arGroup2Intensities[i] = new double[n2];
for (int j = 0; j < n1; j++)
arGroup1Intensities[i][j] = r.NextDouble();
for (int j = 0; j < n2; j++)
arGroup2Intensities[i][j] = r.NextDouble();
}
var res = new GenericVector[N];
NumericVector vGroup1, vGroup2;
for (int i = 0; i < N; i++)
{
vGroup1 = engine.CreateNumericVector(arGroup1Intensities[i]);
Console.WriteLine(vGroup1.Length);
if (i % 10 == 4)
{
engine.ForceGarbageCollection();
engine.ForceGarbageCollection();
}
vGroup2 = engine.CreateNumericVector(arGroup2Intensities[i]);
Console.WriteLine(vGroup2.Length);
engine.SetSymbol("group1", vGroup1);
engine.SetSymbol("group2", vGroup2);
GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
res[i] = testResult;
}
}
示例13: memory
/*
1.5.5
//var blah = x.RowNames;
memoryInitial 50.16 double
netMemBefore 87860 long
blah null string[]
memoryAfterAlloc 62.08 double
netMemAfter 0 long
var blah = engine.Evaluate("rownames(x)").AsCharacter().ToArray();
memoryInitial 50.15 double
netMemBefore 87948 long
blah null string[]
memoryAfterAlloc 65.95 double
netMemAfter 0 long
1.5.6, not waiting for final total memory (otherwise hangs, as with above)
memoryInitial 50.16 double
netMemBefore 88608 long
blah null string[]
memoryAfterAlloc 65.95 double
netMemAfter 98738480 long
memoryInitial 50.16 double
netMemBefore 88572 long
blah null string[]
memoryAfterAlloc 62.08 double
netMemAfter 99319384 long
*/
private static void ReproWorkitem41(REngine engine)
{
var fname = "c:/tmp/rgraph.png";
engine.Evaluate("library(ggplot2)");
engine.Evaluate("library(scales)");
engine.Evaluate("library(plyr)");
engine.Evaluate("d <- data.frame( x = rnorm(1000), y = rnorm(1000), z = rnorm(1000))");
engine.Evaluate("p <- ggplot(d, aes(x = x, y = y, color = z)) + geom_point(size=4.5, shape=19)");
// Use:
engine.Evaluate("png('" + fname + "')");
engine.Evaluate("print(p)");
// but not:
// engine.Evaluate("p");
// engine.Evaluate("dev.copy(png, '" + fname + "')");
// the statement engine.Evaluate("p") does not behave the same as p (or print(p)) directly in the R console.
engine.Evaluate("dev.off()");
}
示例14: ReproWorkitem22
private static void ReproWorkitem22(REngine engine)
{
var statements = @"
parameters <- data.frame(name=paste('x', 1:4, sep=''),
min = c(1, -10, 1, 0.5),
value= c(700, 0, 100, 2),
max = c(1500, 5, 500, 4),
stringsAsFactors=FALSE)
f <- function(i, p) {
runif(1, p[i,'min'], p[i,'max'])
}
";
var df = engine.Evaluate(statements);
var rndParams = "parameters$value <- as.numeric(lapply(1:nrow(parameters), FUN=f, parameters))";
engine.Evaluate("set.seed(0)");
for (int i = 0; i < 1000; i++)
{
engine.Evaluate(rndParams);
//engine.Evaluate("print(parameters)");
GetDataFrame("parameters", engine);
}
}
示例15: ReproDiscussion30824095
private static void ReproDiscussion30824095(REngine e)
{
e.Evaluate("library(cluster)");
e.Evaluate("library(rrcov)");
// plot from R
//to show outlier with method : classic & robust Mve
e.Evaluate("n <- 100 ; spread <- (n/2 - abs(1:n - n/2))/n * 4");
e.Evaluate("X <- data.frame(1:n + spread * rnorm(n), 2 * 1:n + spread * rnorm(n))");
int xAxis = 1;
int yAxis = 2;
e.Evaluate("x<-X[," + xAxis + "] ");
e.Evaluate("y<-X[," + yAxis + "] ");
e.Evaluate("shape <- cov(X)");
e.Evaluate("center<- colMeans(X)");
e.Evaluate("d2.95 <- qchisq(0.95, df = 2)");
//e.Evaluate("gr<- grid(lty=3,col='lightgray', equilogs = 'TRUE')");
//dataform.rconn.Evaluate("mtext('with classical (red) and robust (blue)')");
e.Evaluate("plot(x,y, main='Draw Ellipse ', pch=19,col='black', type='p')");
e.Evaluate("elp<- unname(ellipsoidPoints(shape, d2.95,center))");
e.Evaluate(" lines(elp, col='red' , lty=7 , lwd=2)");
//e.Evaluate("lines(e)");
//e.Evaluate("lines(ellipsoidPoints([email protected], d2 = d2.95, [email protected]), col='blue', lty='7' , lwd='2') ");
// axGraphicsDevice2.RemoveFromConnector();
e.Evaluate("dev.off()");
}