Search code examples
rreshapedata-manipulationreshape2spread

how to spread one variables into columns in r


my df

A   B    C  D
a 2015   1  2
d 2016   2  3
k 2016   2  4
k 2018   3  6

what I need is to do this kind of reshape

A value 2015 2016 2018
a   C    1
a   D    2 
d   C    2
d   D    3
k   C         2
k   D         4
k   C               3
k   D               6

Thank you for your help


Solution

  • Though not completely sure, I think you want this! (because there is no reason why k & C and K & D combination be repeated in two rows!

    library(tidyverse)
    df %>% pivot_longer(!c(A, B)) %>% pivot_wider(id_cols = c(A, name), names_from = B, values_from = value, names_sort = T)
    # A tibble: 6 x 5
      A     name  `2015` `2016` `2018`
      <chr> <chr>  <int>  <int>  <int>
    1 a     C          1     NA     NA
    2 a     D          2     NA     NA
    3 d     C         NA      2     NA
    4 d     D         NA      3     NA
    5 k     C         NA      2      3
    6 k     D         NA      4      6