从 grouped_df 中的每个 df 收集值到列表

Gathering values to a list from each df in grouped_df

我有一个数据框 df:

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

我想获取 new_df,在 spell_num 列中具有唯一值,在列表中收集 id 列中的值:

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

我试过这段代码:

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

其中 gather_ids 是一个函数:

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

但是没用。您能否通过帮助改进此代码或提出更好的方法来帮助我获得所需的输出?谢谢

library(dplyr)

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

输出

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

数据

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))