1

So I have a dataframe that looks like this:

df <- data.frame(ID = c("A","A","A","A","A","B","B","B","B","B","C","C","C","C","C"),
                 code = c(1,2,2,3,3,1,2,2,1,1,3,2,2,1,1),
                 class =  c(2,4,5,5,2,3,2,5,1,2,4,5,3,2,1),
                 n = c(10,10,20,15,25,20,10,10,20,25,10,15,10,15,15))

I want to transpose it, so that the column class becomes rows, and n is spread based on ID, class and n. So it would look like this:

|ID|class|1 |2 |3 |4 |5 |
|A |1    |  |10|  |  |  |
|A |2    |  |  |  |10|20|
|A |3    |  |25|  |  |15|
....
starski
  • 141
  • 6

1 Answers1

2

You could use pivot_wider and arrange to get the column numerically order like this:

library(dplyr)
library(tidyr)
df %>%
  arrange(class) %>%
  pivot_wider(names_from = class, values_from = n) %>%
  arrange(ID, code)
#> # A tibble: 8 × 7
#>   ID     code   `1`   `2`   `3`   `4`   `5`
#>   <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 A         1    NA    10    NA    NA    NA
#> 2 A         2    NA    NA    NA    10    20
#> 3 A         3    NA    25    NA    NA    15
#> 4 B         1    20    25    20    NA    NA
#> 5 B         2    NA    10    NA    NA    10
#> 6 C         1    15    15    NA    NA    NA
#> 7 C         2    NA    NA    10    NA    15
#> 8 C         3    NA    NA    NA    10    NA

Created on 2022-12-27 with reprex v2.0.2

Quinten
  • 35,235
  • 5
  • 20
  • 53