-1

I have a rather big dataframe structured in the following way:

     Date         Item size       
[1,] "2021-01-04" "AA" "23.25"    
[2,] "2021-01-05" "AA" "23.67"    
[3,] "2021-01-06" "AA" "25.20"
[4,] "2021-01-04" "BB" "31.21"    
[5,] "2021-01-05" "BB" "33.27"    
[6,] "2021-01-06" "BB" "35.20"
[7,] "2021-01-04" "CC" "13.25"    
[8,] "2021-01-05" "CC" "13.61"    
[9,] "2021-01-06" "CC" "15.20"

etc.

I would like it to be reformat in the following way:

     Date         AA        BB      CC      
[1,] "2021-01-04" "23.25"   "31.21" "13.25"     
[2,] "2021-01-05" "23.67"   "33.27" "13.61" 
[3,] "2021-01-06" "25.20"   "35.20" "15.20" 

Therefore, for all the different occurrences in the 'Item' column ("AA","BB","CC"), a new column should be created with that name and carrying all the values reported in the 'size' column for that Item. The number of the different occurrences in the 'Item' column is always the same (three "AA", three "BB", three "CC"). As mentioned, my dataframe is rather big (millions of lines), but I used this representative example for the sake of seplicity. Any help or pointer would be greatly appreciated.

Arturo
  • 342
  • 1
  • 4
  • 14
  • 1
    This is likely a duplicate of [this](https://stackoverflow.com/questions/65132384/r-pivot-wider-to-extend-a-dataframe) or [this](https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format) – Mata Dec 02 '21 at 12:54

1 Answers1

0

Use tidyr::pivot_wider.

library(tidyr)
df %>% pivot_wider(names_from = Item, values_from = size)

# A tibble: 3 x 4
  Date          AA    BB    CC
  <chr>      <dbl> <dbl> <dbl>
1 2021-01-04  23.2  31.2  13.2
2 2021-01-05  23.7  33.3  13.6
3 2021-01-06  25.2  35.2  15.2
Maël
  • 45,206
  • 3
  • 29
  • 67