j - 如何在J中将数据数组从宽到长重塑?
问题描述
我喜欢在Jreshape
中复制该功能。
例如,Stata可以reshape
将数据集“从宽到长”。以下是他们文档中的示例 1 :
. use http://www.stata-press.com/data/r11/reshape1.dta
. list
+-------------------------------------------------------+
| id sex inc80 inc81 inc82 ue80 ue81 ue82 |
|-------------------------------------------------------|
| 1 0 5000 5500 6000 0 1 0 |
| 2 1 2000 2200 3300 1 0 0 |
| 3 0 3000 2000 1000 0 0 1 |
+-------------------------------------------------------+
. reshape long inc ue, i(id) j(year)
. list
+-----------------------------+
| id year sex inc ue |
|-----------------------------|
| 1 80 0 5000 0 |
| 1 81 0 5500 1 |
| 1 82 0 6000 0 |
| 2 80 1 2000 1 |
| 2 81 1 2200 0 |
| 2 82 1 3300 0 |
| 3 80 0 3000 0 |
| 3 81 0 2000 0 |
| 3 82 0 1000 1 |
+-----------------------------+
注意。Python Pandas 有一个类似的功能(“堆栈”)。
我了解 J 可以按如下方式导入数据文件(csv 格式)。
load 'web/gethttp'
] dataset =: gethttp 'https://bbbyc.github.io/reshape1.csv'
load 'tables/csv'
] dataInJArray =: fixcsv dataset
得到这个后我迷路了dataInJArray
。我该如何重塑它?感谢任何提示/建议!
解决方案
要使用 J 实际解决您的特定问题,您可以这样做:
NB. t is the data to be stacked:
[ t=: 3 8 $ 1 0 5000 5500 6000 0 1 0 2 1 2000 2200 3300 1 0 0 3 0 3000 2000 1000 0 0 1
1 0 5000 5500 6000 0 1 0
2 1 2000 2200 3300 1 0 0
3 0 3000 2000 1000 0 0 1
您可以适当地选择和组合不同的列
({. ,. 1&{ ,. (2 3 4 & {),. (5 6 7 & {))"1 t
1 0 5000 0
1 0 5500 1
1 0 6000 0
2 1 2000 1
2 1 2200 0
2 1 3300 0
3 0 3000 0
3 0 2000 0
3 0 1000 1
由于这会在组之间留下间隙,因此您适用,/
于整个结果
,/@:(({. ,. 1&{ ,. (2 3 4 & {),. (5 6 7 & {))"1) t
1 0 5000 0
1 0 5500 1
1 0 6000 0
2 1 2000 1
2 1 2200 0
2 1 3300 0
3 0 3000 0
3 0 2000 0
3 0 1000 1
我不确定这概括得有多好,但如果它们已经被适当地组织,则可以在任何数量的记录的表上使用变体。
完成格式化和“年”的引入
[s1=. ,. each <"1 |: s0 NB. years inserted in the next step
+-+-+----+-+
|1|0|5000|0|
|1|0|5500|1|
|1|0|6000|0|
|2|1|2000|1|
|2|1|2200|0|
|2|1|3300|0|
|3|0|3000|0|
|3|0|2000|0|
|3|0|1000|1|
+-+-+----+-+
[s2=. ({. , ,.@:(9 $ 80 81 82"_); }.)s1 NB. 80 81 82"_ creates a verb that returns 80 81 82 given any argument
+-+--+-+----+-+
|1|80|0|5000|0|
|1|81|0|5500|1|
|1|82|0|6000|0|
|2|80|1|2000|1|
|2|81|1|2200|0|
|2|82|1|3300|0|
|3|80|0|3000|0|
|3|81|0|2000|0|
|3|82|0|1000|1|
+-+--+-+----+-+
('id';'year';'sex';'inc';'ue'),:s2
+--+----+---+----+--+
|id|year|sex|inc |ue|
+--+----+---+----+--+
|1 |80 |0 |5000|0 |
|1 |81 |0 |5500|1 |
|1 |82 |0 |6000|0 |
|2 |80 |1 |2000|1 |
|2 |81 |1 |2200|0 |
|2 |82 |1 |3300|0 |
|3 |80 |0 |3000|0 |
|3 |81 |0 |2000|0 |
|3 |82 |0 |1000|1 |
+--+----+---+----+--+
推荐阅读
- javascript - 如何将 Dart POST 请求转换为 JavaScript?
- angular - 如何更改 Ag-Grid 状态栏的状态面板行数名称
- docker - 运行 Docker 时 IPTable 出错(RULE_APPEND 失败)
- python - 我怎样才能弹出一个字符串?
- c# - 使用 OleDbConnection.Open() 时 Access-DB(.accdb) 访问崩溃应用程序
- testing - mantis中的错误1200有解决方案吗?
- javascript - After Effects:如何让一个表达在另一个已经结束后开始?
- php - 使用 implode() PHP 时数组到字符串的转换
- class - 将 Fortran 无限类可选 ARRAY 参数传递给模块中的多个子例程
- python - VAR 模型立即收敛到平均值