F#中的类型转换

Jam*_*xon 1 f# r

我正在通过F#脚本将excel数据导入到R回归中.代码是:

let path = @"C:\Data\DataForRegression.csv"
let fileStream = new FileStream(path,FileMode.Open,FileAccess.Read)
let streamReader = new StreamReader(fileStream)
let contents = streamReader.ReadToEnd()

let cleanContents =
    contents.Split([|'\n'|])
    |> Seq.map(fun line -> line.Split([|','|]))
    |> Seq.skip(1)
    |> Seq.map(fun values ->
        Double.Parse(values.[0]),
        Double.Parse(values.[1]),
        DateTime.Parse(values.[2]).ToShortDateString(),
        Int32.Parse(values.[3]),
        Int32.Parse(values.[4]),
        Int32.Parse(values.[5]),
        Int32.Parse(values.[6]))

//open R
let environmentPath = System.Environment.GetEnvironmentVariable("PATH")
let binaryPath = @"C:\Program Files\R\R-3.0.1\bin\x64"
System.Environment.SetEnvironmentVariable("PATH",environmentPath+System.IO.Path.PathSeparator.ToString()+binaryPath)

let engine = RDotNet.REngine.CreateInstance("RDotNet")
engine.Initialize()

let pmpm = engine.CreateNumericVector(cleanContents |> Seq.map (fun (a,b,c,d,e,f,g) -> a))
engine.SetSymbol("pmpm",pmpm)
Run Code Online (Sandbox Code Playgroud)

第一行数据如下所示:

$ 66.92,0.9458,扬13,0,0,0,1

当我运行它时,我得到了这个:

System.FormatException:输入字符串的格式不正确.
at System:Number.ParseDouble(String value,NumberStyles options,NumberFormatInfo numfmt)at FSI_0002.cleanContents@18.Invoke(String [] values)in C:\ TFS\Tff.RDotNetExample_Solution\Tff.RDotNetExample\RegressionUsingExcelImport.fsx:第19行在Microsoft.FSharp.Collections.IEnumerator.map@109.DoMoveNext(b&)at Microsoft.FSharp.Collections.IEnumerator.MapEnumerator 1.System-Collections-IEnumerator-MoveNext()at System.Linq.Enumerable.Count [TSource]( IEnumerable 1..ctor(REngine引擎,SymbolicExpressionType类型,IEnumerable1.System-Collections-IEnumerator-MoveNext() at Microsoft.FSharp.Collections.IEnumerator.map@109.DoMoveNext(b& )
at Microsoft.FSharp.Collections.IEnumerator.MapEnumerator
1 source) at RDotNet.Vector1 vector) at RDotNet.NumericVector..ctor(REngine engine, IEnumerable1个向量)at RDotNet.REngineExtension.CreateNumericVector(REngine engine,IEnumerable`1 vector)at.$ FSI_0002.main @()in C:\ TFS\Tff.RDotNetExample_Solution\Tff.RDotNetExample\RegressionUsingExcelImport.fsx:line 35 Stopped错误

有没有人知道我需要做什么来转换数据?我的预感是它不喜欢'$' - 但它在Double.Parse中没有加载任何问题(除非它没有被评估?).

提前致谢

Gus*_*rra 5

使用以下内容:

Double.Parse(values.[0], NumberStyles.AllowDecimalPoint ||| NumberStyles.AllowCurrencySymbol, CultureInfo("en-US"))
Run Code Online (Sandbox Code Playgroud)

请参阅http://msdn.microsoft.com/en-us/library/fd84bdyt.aspx:

使用NumberStyles.Float和NumberStyles.AllowThousands标志的组合来解释s参数.这意味着允许使用空格和千位分隔符,例如,货币符号则不允许.为了更好地控制s中允许哪些样式元素成功进行解析操作,请调用Double.Parse(String,NumberStyles)或Double.Parse(String,NumberStyles,IFormatProvider)方法.

因此,即使您的默认文化已经是具有$货币符号的文化,您仍然必须明确使用NumberStyles.AllowCurrencySymbol