Melt和Cast是处理R中数据的常用操作.在F#中,它将是相同类型或接近它的某些记录序列.
您是否了解F#中的任何此类功能?
(如果没有,谁会有兴趣制作一些强类型版本......)
更多信息:
Melt以表格作为输入.它有列标题(我们的记录字段)和一系列行.这些列可以分为一组"标识符"和一组"变量"
Melt将此表放在一个新的规范形式中,列现在是:标识符,名为@"variable"的列,名为@"value"的列
如果你原来有10个''变量',比如大小,重量等等,你将为每个先前的记录,规范形式的10条记录,@'变量'列中的值填充前一个标题来自'变量'的列
相反,施放从熔化的表中重建表格.
R中的一个简短示例melt采用如下所示的data(dat):
a b c
1 1 0.48411551 0.2372291
2 2 0.58850308 0.3968759
3 3 0.74412592 0.9718320
4 4 0.93060118 0.8665092
5 5 0.01556804 0.2512399
Run Code Online (Sandbox Code Playgroud)
并使它看起来像这样:
> melt(dat,id.vars = "a")
a variable value
1 1 b 0.48411551
2 2 b 0.58850308
3 3 b 0.74412592
4 4 b 0.93060118
5 5 b 0.01556804
6 1 c 0.23722911
7 2 c 0.39687586
8 3 c 0.97183200
9 4 c 0.86650918
10 5 c 0.25123992
Run Code Online (Sandbox Code Playgroud)
cast 基本上是相反的.
这两项行动每天都非常强大.一旦你拥有它们就会改变你的想法,就像FP一样.
假设melt与 SQL Server 类似unpivot,这应该可以解决问题:
let melt keys (table: DataTable) =
let out = new DataTable()
let keyCols, otherCols =
table.Columns
|> Seq.cast<DataColumn>
|> Seq.toArray
|> Array.partition (fun c -> keys |> Seq.exists (fun k -> k = c.ColumnName))
for c in keyCols do
out.Columns.Add(c.ColumnName) |> ignore
out.Columns.Add("Key", typeof<string>) |> ignore
out.Columns.Add("Value") |> ignore
for r in table.Rows do
for c in otherCols do
let values = [|
for c in keyCols do yield r.[c]
yield box c.ColumnName
yield r.[c]
|]
out.Rows.Add(values) |> ignore
out
Run Code Online (Sandbox Code Playgroud)
这里有一个小测试来尝试一下:
let table = new DataTable()
[|"Country", typeof<string>
"2001", typeof<int>
"2002", typeof<int>
"2003", typeof<int>|]
|> Array.map (fun (name, typ) -> new DataColumn(name, typ))
|> table.Columns.AddRange
[
"Nigeria", 1, 2, 3
"UK", 2, 3, 4
]
|> List.iter (fun (a, b, c, d) -> table.Rows.Add(a, b, c, d) |> ignore)
let table2 = table |> melt ["Country"]
table2.Rows
|> Seq.cast<DataRow>
|> Seq.iter (fun r ->
for (c: DataColumn) in table2.Columns do
printfn "%A: %A" c.ColumnName r.[c]
printfn "")
Run Code Online (Sandbox Code Playgroud)
这产生
"Country": "Nigeria"
"Key": "2001"
"Value": "1"
"Country": "Nigeria"
"Key": "2002"
"Value": "2"
...
Run Code Online (Sandbox Code Playgroud)
假设cast采用另一种方式(即pivot),您应该能够获取此代码并提出翻译。
如果您经常这样做,您可能会发现将数据加载到 SQL Server 并使用内置运算符更容易。