gpt4 book ai didi

r - 在 F# 中,R 中有没有像 'melt' 或 'cast' 这样的操作?

转载 作者:行者123 更新时间:2023-12-04 21:22:35 24 4
gpt4 key购买 nike

Melt 和 Cast 是在 R 中处理数据的流行操作。
在 F# 中,这将是相同类型或接近它的记录序列。

您知道 F# 中的任何此类函数吗?

(如果没有,谁会对制作它们的强类型版本感兴趣......)

更多信息:

Melt 将表格作为输入。
它有列标题(我们的记录字段)和一系列行。
这些列可以分为一组“标识符”和一组“变量”

Melt 将此表置于新的规范形式中,列现在为:
标识符,名为@"variable"的列,名为@"value"的列

如果您最初有 10 个“变量”,例如大小、重量等。对于之前的每条记录,您将拥有 10 条规范形式的记录,@'variable' 列中的值填充为前一个的标题“变量”中的列

相反,类型转换,从熔化的 table 重建一张 table 。

R 中的一个简短示例,melt获取如下所示的数据 ( 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

并使它看起来像这样:
> 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
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

这是一个小测试来尝试一下:
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 "")

这产生
"Country": "Nigeria"
"Key": "2001"
"Value": "1"

"Country": "Nigeria"
"Key": "2002"
"Value": "2"

...

假设 cast反过来(即 pivot ),您应该能够使用此代码并进行翻译。

如果您经常这样做,您可能会发现将数据加载到 SQL Server 并使用内置运算符更容易。

关于r - 在 F# 中,R 中有没有像 'melt' 或 'cast' 这样的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9522521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com