How to create multiple columns from categories or values in one existing column?

Hi everyone,
I am trying to turn values from one column into columns of their own, and fill their fields with their data corresponding to certain groups. Here is an example...

...
From

group_name Year Count
p1 2010 5
p2 2010 8
p3 2010 7
p1 2011 1
p2 2011 3
p3 2011 3
p4 2011 1
p1 2012 1
p2 2012 2
p3 2012 1

To

group_name 2010 2011 2012
p1 5 1 1
p2 8 3 2
p3 7 3 1
p4 1

...

Here is one method.

DF <- data.frame(group=c("p1","p2","p3","p1","p2","p3","p4","p1","p2","p3"),
                 year = c(2010,2010,2010,2011,2011,2011,2011,2012,2012,2012),
                 Value = 1:10)
DF
#>    group year Value
#> 1     p1 2010     1
#> 2     p2 2010     2
#> 3     p3 2010     3
#> 4     p1 2011     4
#> 5     p2 2011     5
#> 6     p3 2011     6
#> 7     p4 2011     7
#> 8     p1 2012     8
#> 9     p2 2012     9
#> 10    p3 2012    10
library(tidyr)
DFwide <- pivot_wider(DF, names_from = "year", values_from = "Value")
DFwide
#> # A tibble: 4 × 4
#>   group `2010` `2011` `2012`
#>   <chr>  <int>  <int>  <int>
#> 1 p1         1      4      8
#> 2 p2         2      5      9
#> 3 p3         3      6     10
#> 4 p4        NA      7     NA

Created on 2023-03-28 with reprex v2.0.2

1 Like

FJCC you are my hero as always, thank you.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.