Home > Mobile >  From long to wide for ALL the columns
From long to wide for ALL the columns

Time:12-06

I have a dataset like 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))

I want to go from long to wide FOR ALL VARIABLES but (month, type) like bb with a dataset with much more columns.

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))

I have tried pivot_wider() and reshape() without success.

Any clue?

CodePudding user response:

You could tidyr::pivot_wider like so:

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

CodePudding user response:

reshape from base R can be used if we take care of duplicate by creating a sequence column

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
  • Related