所有列从长到宽

From long to wide for ALL the columns

我有一个像 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() 都没有成功。

有线索吗?

你可以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

reshape from base R 如果我们通过创建序列列

来处理重复项,则可以使用
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