Search code examples
rdplyrtidyversespread

gather and spread with dplyr easy example


I am trying to get the philosophy of gather and spread write. if you have a a data frame that looks like this:

group=c("A","A","A","B","B","B")
time =c(10,20,30,10,20,30)
value=c(20,40,80,10,10,20)

data= data.frame(group,time,value)

group time value
  A   10    20
  A   20    40
  A   30    80
  B   10    10
  B   20    10
  B   30    20

How can you get here

A   B   time
20 10    10
40 10    20
80 20    30

Solution

  • We can use pivot_wider

    library(dplyr)
    library(tidyr)
    data %>% 
       pivot_wider(names_from = group, values_from = value)
    

    -output

    # A tibble: 3 x 3
    #   time     A     B
    #  <dbl> <dbl> <dbl>
    #1    10    20    10
    #2    20    40    10
    #3    30    80    20