【问题标题】:How to create a dataframe of multiple types with the RTypeProvider如何使用 RTypeProvider 创建多种类型的数据框
【发布时间】:2017-01-21 15:21:11
【问题描述】:

似乎RTypeProvider 只能处理相同类型的namedParams。是这样吗?

例如,

open RDotNet
open RProvider 

type foo = {
    Which: string
    Qty: float option
    }    

let someFoos = [{Which = "that"; Qty = Some 4.0}; {Which = "other"; Qty = Some 2.0}]

let thingForR = 
    namedParams [
        "which", someFoos |> List.map (fun x -> x.Which); 
        "qty", someFoos |> List.map (fun x -> x.Qty);
        ]
    |> R.data_frame

不起作用,因为我在 x.Qty 上收到错误提示

This expression was expected to have type 
  string
but here has type
  float option

如果我在thingForR let 中颠倒顺序,则会得到相反的错误:

let thingForR = 
    namedParams [
        "qty", someFoos |> List.map (fun x -> x.Qty); 
        "which", someFoos |> List.map (fun x -> x.Which);
        ]
    |> R.data_frame

这里,x.Which 的错误是

This expression was expected to have type
  float option
but here has type
  string

namedParams中的字典不能有不同的类型吗?如果是这样,您如何在 F# 中创建具有不同类型的数据框并将它们传递给 R?

【问题讨论】:

  • 这是一个 F# 错误,欢迎使用强类型语言 :-) 你需要 box 它。但是您也会遇到选项类型的问题。我不知道为什么,但没有转换器。让我先搜索一下相关答案。

标签: r f# type-providers


【解决方案1】:

您需要将字典中的值装箱。这样他们都只是对象。所以:

let thingForR = 
    namedParams [
        "which", box (someFoos |>  List.map (fun x ->  x.Which) ); 
        "qty", box  (someFoos |> List.map (fun x ->   x.Qty) |> List.map (Option.toNullable >> float));
        ]
    |> R.data_frame

给我:

val thingForR :
SymbolicExpression = 哪个数量
1 那 4
其他 2 个 2

请参考您之前在float option 上的问题,将Option list 转换为float list。如有必要,也可以string option

您可以通过 Deedle(如果不是选项值):

let someFoos' = [{Which = "that"; Qty =  4.0}; {Which = "other"; Qty =  2.0}]
let df' = someFoos' |> Frame.ofRecords
df' |> R.data_frame 

【讨论】:

  • 顺便说一句,多个映射和选项转换可能看起来很难看,但实际上如果你经常使用它,你最终会为它定义辅助函数。
  • 啊哈!完美的。谢谢。是的,将float option 转换为NaN 是必要的,将string option 转换为null 也是必要的。只是决定不要把这个问题搞得一团糟。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-27
相关资源
最近更新 更多