【问题标题】:How To Make df wider with multiple columns [duplicate]如何使用多列使df更宽[重复]
【发布时间】:2019-05-17 20:42:04
【问题描述】:

我正在尝试找出一种快速旋转此表的方法。我的输入表是这样的

+------+------+------+
| FY   | col1 | col2 |
+------+------+------+
| 2019 | 34   | 28   |
+------+------+------+
| 2018 | 22   | 39   |
+------+------+------+

我希望我的输出表是

+-----------+-----------+-----------+-----------+
| col1.2018 | col1.2019 | col2.2018 | col2.2018 |
+-----------+-----------+-----------+-----------+
| 22        | 34        | 39        | 28        |
+-----------+-----------+-----------+-----------+

最快的方法是什么?我尝试使用 reshape 和 tidyr 但我没有得到想要的输出。任何指导或方向表示赞赏

编辑:这不是所指出的其他问题的完全重复。虽然相似,但又不一样

【问题讨论】:

    标签: r dplyr tidyr


    【解决方案1】:

    一个选项是将gather 列('col1'、'col2')转换为长格式,gather),unite 'key' 和'FY' 列,然后spread 返回“宽”格式

    library(tidyverse)
    gather(df1, key, val, col1:col2) %>%
         unite(key1, key, FY, sep=".") %>%
         spread(key1, val)
    #   col1.2018 col1.2019 col2.2018 col2.2019
    #1        22        34        39        28
    

    数据

    df1 <- structure(list(FY = c(2019, 2018), col1 = c(34, 22), col2 = c(28, 
     39)), class = "data.frame", row.names = c(NA, -2L))
    

    【讨论】:

    • 超快.. 上帝啊,非常感谢您.. 我会在接下来的 8 分钟内接受您的解决方案.. :)
    猜你喜欢
    • 2021-05-08
    • 1970-01-01
    • 2021-01-14
    • 2021-11-02
    • 2020-12-17
    • 2016-03-20
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多