如何使用 R.NET 执行变点分析

How to perform Change Point Analysis using R.NET

如何使用 R.NET 执行变点分析。我正在使用下面的代码

REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance();
double[] data = new double[] { 1, 2, 3, 4, 5, 6 };
NumericVector vector = engine.CreateNumericVector(data);
engine.SetSymbol("mydatapoints", vector);
engine.Evaluate("library(changepoint)");
engine.Evaluate("chpoints = cpt.mean(mydatapoints, method="BinSeg")");
DynamicVector result = engine.Evaluate("x<-cpts(chpoints)").AsVector(); ;
engine.Dispose();

我在 engine.Evaluate("library(changepoint)");

收到以下错误

Error in library(changepoint) : there is no package called 'changepoint'

编辑#1

changepoint 包应该被显式安装,默认情况下不存在。使用 RGui -> Packages -> Load package 安装它。

现在错误已经改成了

Status Error for chpoints = cpt.mean(mydatapoints, method=”BinSeg”) : unexpected input

编辑#2

修复前两个错误后,第二个 Evaluate 语句中出现以下错误。

Error in BINSEG(sumstat, pen = pen.value, cost_func = costfunc, minseglen = minseglen, : Q is larger than the maximum number of segments 4

同样的错误出现在 R 以及使用这些命令

value.ts <- c(29.89, 29.93, 29.72, 29.98)
chpoints = cpt.mean(value.ts, method="BinSeg")

错误不在您的调用代码中,而是在您对 R 的使用中(正如您现在显然意识到的那样)。因此,将此标记为与 rdotnet 或 c-sharp 有关的标签似乎具有误导性:

mydatapoints <- c(1, 2, 3, 4, 5, 6 )
library(changepoint);
chpoints = cpt.mean(mydatapoints, method="BinSeg");
#Error in BINSEG(sumstat, pen = pen.value, cost_func = costfunc, minseglen = minseglen,  : 
#  Q is larger than the maximum number of segments 4

我不确定你的意图。变点分析通常需要成对的数据点...... x-y 和所有爵士乐。给 R 回归函数完美的线性数据也是不明智的。它经常导致不可逆矩阵。

我建议您使用 https://whosebug.com/search?q=%5Br%5D+changepoint 进行搜索,找到一段简单的代码来构建您的 REngine 调用方案。

数据点应该在时间序列中转换。

REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance();
double[] data = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
NumericVector vector = engine.CreateNumericVector(data);
engine.Evaluate("library(changepoint)");
engine.SetSymbol("values", vector);
engine.Evaluate("values.ts = ts(values, frequency = 12, start = c(2017, 1))");
engine.Evaluate("chpoints = cpt.mean(values.ts, method=\"BinSeg\")");
var result = engine.GetSymbol("chpoints");
engine.Dispose();

现在寻找如何在 C# 中返回结果,chpointsplot(chpoints)

的结果