I have the following data frame labelled df1:
df1 <- data.frame(ID = c("A", "A", "A", "B", "B", "B", "B"),
NO. = c(2,8,7,1,4,9,6),
RANK = c(1,2,3,1,2,3,4))
It looks like this:
| ID | NO. | RANK
------------------
| A | 2 | 1
| A | 8 | 2
| A | 7 | 3
| B | 1 | 1
| B | 4 | 2
| B | 9 | 3
| B | 6 | 4
My data frame has many ID's and the 'RANK' column can go as high as 30 but this is just a snapshot.
I wish to transpose the NO. column based on the ID and the RANK like so:
| ID | NO._RANK_1 | NO._RANK_2 | NO._RANK_3 | NO._RANK_4
-------------------------------------------------------------
| A | 2 | 8 | 7 |
| B | 1 | 4 | 9 | 6
Ideally I would like this as a separate data frame (df2).
I tried:
library(dplyr)
library(tidyr)
df2 <- df1 %>%
group_by(ID) %>%
spread(RANK, NO.)
But this returns the numbers in separate columns AND rows like so:
| ID | 1 | 2 | 3 | 4
------------------
| A | 2 | NA | NA | NA
| A | NA | 8 | NA | NA
| A | NA | NA | 7 | NA
| B | 1 | NA | NA | NA
| B | NA | 4 | NA | NA
| B | NA | NA | 9 | NA
| B | NA | NA | NA | 6