Long to wide creating new columns and populating values from previous column

57 Views Asked by At

The answer to my question might be available and I am just no phrasing it correctly.

I have something similar to this:

ID Fruit Date
1 Apple 1.12.22
1 Orange 3.10.20
2 Blueberry 12.8.06
3 Apple 15.9.08
3 Apple 12.2.02
3 Tomato 3.7.22
. . .
. . .
. . .

I am using Rstudios and would like to change the above to a wide format and also automatically create new columns and populate values with the dates in ascending order. The maximum column number will depend on the ID with the most fruit.

I would like it to look like this:

ID Fruit1 Fruit2 Fruit3 ...
1 3.10.20 1.12.23 0 ...
2 12.8.06 0 0 ...
3 12.2.02 15.9.08 3.7.22 ...
. . . . ...

As you have noticed I do not actually need the names of the fruit for the output, just the dates. I not know what the max n is of Fruitn as the data set is huge.

I hope the above makes sense.

I haven't been able to find the solution online, but that is probably because I am not explaining it correctly.

1

There are 1 best solutions below

3
On
library(tidyverse) 
df %>%
   mutate(name = rank(dmy(Date)), .by = ID) %>%
   pivot_wider(id_cols = ID, values_from = Date,
               names_prefix = 'Fruit', names_sort = TRUE,  values_fill = '0')

# A tibble: 3 × 4
     ID Fruit1  Fruit2  Fruit3
  <int> <chr>   <chr>   <chr> 
1     1 3.10.20 1.12.22 0     
2     2 12.8.06 0       0     
3     3 12.2.02 15.9.08 3.7.22