Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group by two columns and make third one wide of r data frame

I have a data frame that has the following structure:

df <- data.frame("first" = c("A","A","B","B","B"),
           "second" = c("C","C","D","D","Z"),
           "third" = c("E","F","G","H","I"))

  first second third
1     A      C     E
2     A      C     F
3     B      D     G
4     B      D     H
5     B      Z     I

I’m trying to group this by the first two columns and make the third one wide for all the values. So like this:

  first second third fourth
1     A      C     E      F
2     B      D     G      H
3     B      Z     I   <NA>

The new colnames don’t matter though. Just one row for every unique ‘first’ and ‘second’ column with as many new columns as needed. I tried nesting and unnesting wide, but that doesn’t work for me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One option would be to first add a row identifier per group which could then be used a the names_from argument using tidyr::pivot_wider:

library(tidyr)
library(dplyr)

df |>
  group_by(first, second) |>
  mutate(row = seq(n())) |>
  ungroup() |>
  pivot_wider(names_from = "row", values_from = "third") |>
  rename(third = 3, fourth = 4)
#> # A tibble: 3 × 4
#>   first second third fourth
#>   <chr> <chr>  <chr> <chr> 
#> 1 A     C      E     F     
#> 2 B     D      G     H     
#> 3 B     Z      I     <NA>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading