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

Gathering values to a list from each df in grouped_df

I have a dataframe df:

spell_num id
1 15
2 16
2 17
3 14
4 18
4 19
4 20

and I want to get the new_df, with unique values in spell_num column and values from the id column collected in a list:

spell_num id
1 list(15)
2 list(16,17)
3 list(14)
4 list(18,19,20)

I tried this code:

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

  new_df <- df %>%
    dplyr::group_by(spell_num) %>%
    dplyr::group_map(~gather_ids) %>%
    dplyr::slice(1)

where gather_ids is a function:

gather_ids <- function(x) {
  result <- x %>%
    dplyr::mutate(ids_lst = as.list(x$id))
  result
}

but it didn’t work. Can you help me get the desired output either by helping to improve this code or suggesting a better approach? Thanks

>Solution :

library(dplyr)

df %>% 
  group_by(spell_num) %>% 
  summarise(id = list(list(ID)))

Output

spell_num   ID
1           list(15) 
2           list(16:17) 
3           list(14) 
4           list(18:20)

Data

df <- structure(list(spell_num = c(1L, 2L, 2L, 3L, 4L, 4L, 4L), ID = c(15L, 
16L, 17L, 14L, 18L, 19L, 20L)), class = "data.frame", row.names = c(NA, 
-7L))
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