-1

I have dataframe which is pretty similar to following

index date result
AAA111 19/05/2021 Win
AAA111 29/05/2021 Lose
AAA112 19/05/2021 Win
AAA112 24/05/2021 Win
AAA113 29/05/2021 Lose

I would like to get something like this

index date_1 date_2 result_day_1 result_day_2
AAA111 19/05/2021 29/05/2021 Win Lose
AAA112 19/05/2021 24/05/2021 Win Win
AAA113 29/05/2021 NA Lose NA

Not all the index have same number of days as above.

1 Answers1

1

We could use pivot_wider

library(dplyr)
library(tidyr)
library(data.table)
df1 %>%
    mutate(nm =  rowid(index)) %>% 
    pivot_wider(names_from = nm, values_from = c(date, result))

-output

# A tibble: 3 × 5
  index  date_1     date_2     result_1 result_2
  <chr>  <chr>      <chr>      <chr>    <chr>   
1 AAA111 19/05/2021 29/05/2021 Win      Lose    
2 AAA112 19/05/2021 24/05/2021 Win      Win     
3 AAA113 29/05/2021 <NA>       Lose     <NA>    

Or with data.table

library(data.table)
dcast(setDT(df1), index ~ rowid(index), value.var = c('date', 'result'))
    index     date_1     date_2 result_1 result_2
1: AAA111 19/05/2021 29/05/2021      Win     Lose
2: AAA112 19/05/2021 24/05/2021      Win      Win
3: AAA113 29/05/2021       <NA>     Lose     <NA>

data

df1 <- structure(list(index = c("AAA111", "AAA111", "AAA112", "AAA112", 
"AAA113"), date = c("19/05/2021", "29/05/2021", "19/05/2021", 
"24/05/2021", "29/05/2021"), result = c("Win", "Lose", "Win", 
"Win", "Lose")), class = "data.frame", row.names = c(NA, -5L))
akrun
  • 874,273
  • 37
  • 540
  • 662