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:
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
CodePudding user response:
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))