0

How could I spread gear values using cyl as a key column?

Code

mtcars %>%
  select(cyl, gear)%>%
  spread(cyl, gear)

Error

Error: Duplicate identifiers for rows (3, 8, 9, 18, 19, 20, 21, 26, 27, 28, 32), (1, 2, 4, 6, 10, 11, 30), (5, 7, 12, 13, 14, 15, 16, 17, 22, 23, 24, 25, 29, 31)

Desired output

cyl gear
4 4,4,4,4,4,4,5,5,4
6 4,4,3,4,4,5
8 3,3,3,3,3,3,3,3,5,5
ferrelwill
  • 771
  • 2
  • 8
  • 20
  • Add row number like so `mtcars %>% mutate(rn = row_number()) %>% select(...)` – CPak Aug 13 '18 at 20:12
  • I tried `mutate(rn = row_number())` as mentioned in the previous posts but didn't get what I wanted. @CPak – ferrelwill Aug 13 '18 at 20:15
  • 1
    Does it work and the output is not what you want? Or does it throw an error? If the first, edit your post to describe why the output is not what you want and display desired output – CPak Aug 13 '18 at 20:18
  • As a guess - modify to `select(rn, cyl, gear)` and `spread(cyl, gear, fill=0)` – CPak Aug 13 '18 at 20:20
  • @CPak Nope, it doesn't work. I added the desired output as you suggested. – ferrelwill Aug 13 '18 at 21:26
  • @Cpak, it doesn't work when I used the code as suggested before. Can you please untag "duplicate post". – ferrelwill Aug 13 '18 at 21:57
  • 2
    Try like this: `mtcars %>% select(cyl,gear) %>% group_by(cyl) %>% summarize(gear = paste0(gear, collapse=","))` – Mako212 Aug 13 '18 at 22:05

0 Answers0