【问题标题】:From long to wide for ALL the columns所有列的从长到宽
【发布时间】:2022-01-11 03:38:02
【问题描述】:

我有一个像 aa 这样的数据集:

aa <- data_frame(month = c(1, 1, 2, 2), 
                 type = c("most", "least", "most", "least"),
                 value = c(0.2, 0.8, 1, 0.1),
                 NP = c(4, 2, 0, 6),
                 NO = c(1, 5, 2, 4))

我想从长到宽 FOR ALL VARIABLES 但是(月份,类型)像 bb 这样的数据集包含更多列。

bb <- data_frame(month = c(1, 2), 
                 value_most = c(0.2, 1),
                 value_least = c(0.8, 0.1),
                 NP_most = c(4,  0),
                 NP_least = c(2,6),
                 NO_most = c(1, 2),
                 NO_least = c(5, 4))

我试过 pivot_wider()reshape() 都没有成功。

有什么线索吗?

【问题讨论】:

    标签: r dplyr pivot reshape


    【解决方案1】:

    如果我们通过创建序列列来处理重复,则可以使用来自base Rreshape

    reshape(transform(aa, rn = ave(seq_along(month), month, type, 
       FUN = seq_along)), timevar = "type", idvar = c("rn", "month"),
          direction = "wide")[-2]
      month value.most NP.most NO.most value.least NP.least NO.least
    1     1        0.2       4       1         0.8        2        5
    3     2        1.0       0       2         0.1        6        4
    

    【讨论】:

      【解决方案2】:

      你可以像这样tidyr::pivot_wider

      library(tidyr)
      
      pivot_wider(aa, names_from = type, values_from = -c(month, type))
      #> # A tibble: 2 × 7
      #>   month value_most value_least NP_most NP_least NO_most NO_least
      #>   <dbl>      <dbl>       <dbl>   <dbl>    <dbl>   <dbl>    <dbl>
      #> 1     1        0.2         0.8       4        2       1        5
      #> 2     2        1           0.1       0        6       2        4
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 2016-09-16
        • 2019-12-24
        • 2020-11-18
        • 2019-11-13
        • 2021-09-04
        相关资源
        最近更新 更多