将DataTable转换为列表< double>在R.NET [英] Convert DataTable to List<double> in R.NET
问题描述
我试图使用后台R和前端C#使用R.NET连接器进行项目。
我想将DataTable转换为List,然后将其转换为NumericMatrix,因为R无法处理DataTable。
I'm trying to make a project using backend R and frontend C# using R.NET connector. I want to convert a DataTable to a List and then convert it to NumericMatrix, because R can't process DataTable.
但是当到达以下行时:
double r = Convert.ToDouble(row);
发生这个错误:
输入字符串格式不正确。
Input string was not in a correct format.
这是我的代码:
NumericMatrix matadata;
int nkolom = dataawal.Columns.Count;
if (nkolom > 1)
{
for (int j = 1; j < nkolom; j++)
{
int kol = dataawal.Columns[j].Ordinal;
List<double> s = new List<double>();
for (int i = 0; i < dataawal.Rows.Count; i++)
{
String row = dataawal.Rows[i].ItemArray[kol].ToString();
if (String.IsNullOrEmpty(row))
{
break;
}
else
{
double r = Convert.ToDouble(row); // NOTE Error comes here!
s.Add(r);
}
}
String nokol = Convert.ToString(j + 1);
NumericVector v = engine.CreateNumericVector(s);
engine.SetSymbol("dum", v);
matadata = engine.Evaluate("matdt=matrix(cbind(matdt,dum),ncol=" + nokol + ")").AsNumericMatrix();
}
}
推荐答案
,当您不确定表示双重值的字符串值的正确性时,您应该诉诸 double.TryParse 。如果字符串不能被识别为有效的双倍,则此方法不会引发异常,而是返回false,您可以跳过(或假定零)违规行。
Usually, when you are uncertain about the correctness of a string value representing a double value you should resort to double.TryParse. This method doesn't throw an exception if the string cannot be recognized as a valid double, instead it return false and you are able to skip (or assume zero) the offending row.
这样的事情
...
else
{
double r;
// if tryparse returns true then r has received the converted value
if(double.TryParse(row, out r))
s.Add(r);
}
...
然而,您可能会遇到其他问题,如值这是一个有效的双倍,但用当前语言环境设置无效的十进制格式表示。在这种情况下,您需要一种不同形式的double.TryParse。也接受实现 IFormatProvider
接口的类的实例。
However you could have other problems like a value that is a valid double but expressed with a decimal formatting not valid for your current locale settings. In this case you need a different form of double.TryParse. The one that accepts also an instance of a class that implements the IFormatProvider
interface.
例如,假设你的要使用 it-IT
语言环境(其中逗号用十进制分隔整数部分)格式化,则应使用
For example, assuming that your wanna be doubles are formatted using the it-IT
locale (where a comma delimits the integer part from the decimal) then you should use
CultureInfo ci = new CultureInfo("it-IT");
...
else
{
double r;
if(double.TryParse(row, NumberStyles.AllowDecimalPoint, ci, out r))
s.Add(r);
}
...
这篇关于将DataTable转换为列表< double>在R.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!