Convert data from long format to wide format with multiple measure columns

前端 未结 5 2113
灰色年华
灰色年华 2020-11-22 02:27

I am having trouble figuring out the most elegant and flexible way to switch data from long format to wide format when I have more than one measure variable I want to bring

5条回答
  •  野性不改
    2020-11-22 03:07

    The pivot_wider() function is tidyr's 2nd generation approach (released in tidyr 1.0.0).

    library(magrittr); requireNamespace("tidyr");
    
    my.df %>%
      tidyr::pivot_wider(
        names_from  = c(TIME), # Can accommodate more variables, if needed.
        values_from = c(X, Y)
      )
    

    Result:

    # A tibble: 3 x 11
      ID      X_1   X_2   X_3   X_4   X_5   Y_1   Y_2   Y_3   Y_4   Y_5
                
    1 A         1     4     7    10    13    16    19    22    25    28
    2 B         2     5     8    11    14    17    20    23    26    29
    3 C         3     6     9    12    15    18    21    24    27    30
    

    This is probably preferable to the previous tidyr approach (that uses a combination of gather() and spread()).

    More capabilities are described in the pivoting vignette. This example is particularly concise because your desired specifications match the defaults of the id_cols and names_sep.

提交回复
热议问题