-1

I have the following dataframe which I am trying to prepare for pivoting.

Identifier Data
X0001 A
X0002 B
X0002 C
X0003 G
X0004 B
X0005 B
X0005 C
X0005 D

I'm trying to add a count for the number of times the same identifier has appeared as a 3rd column which I can then use as column headers to pivot the data.

Identifier Data Count
X0001 A 1
X0002 B 1
X0002 C 2
X0003 G 1
X0004 B 1
X0005 B 1
X0005 C 2
X0005 D 3

Final Pivoted Version

Identifier 1 2 3
X0001 A
X0002 B C
X0003 G
X0004 B
X0005 B C D

would greatly appreciate if someone has any ideas on how I can add the Count column required.

Thanks.

Merome
  • 9
  • 3

1 Answers1

0
df %>% group_by(Identifier) %>%
  mutate(d = row_number()) %>%
  pivot_wider(id_cols = Identifier, names_from = d, values_from = Data)

# A tibble: 5 x 4
# Groups:   Identifier [5]
  Identifier `1`   `2`   `3`  
  <chr>      <chr> <chr> <chr>
1 X0001      A     NA    NA   
2 X0002      B     C     NA   
3 X0003      G     NA    NA   
4 X0004      B     NA    NA   
5 X0005      B     C     D  
AnilGoyal
  • 25,297
  • 4
  • 27
  • 45