根据它们所属的列表类别按列的每个值分组

Grouping by each value of a column based on the categories of a list they fall into

今天非常具有挑战性,所以我想不出任何新的想法,所以这个问题的解决方案对你来说可能很明显。我有一个非常简单的数据框,如下所示:

structure(list(user_id = c(101, 102, 102, 103, 103, 106, 107, 
111), phone_number = c(4030201, 4030201, 4030202, 4030202, 4030203, 
4030204, 4030205, 4030203), id = 1:8), class = "data.frame", row.names = c(NA, 
-8L))

还有一个列表:

list(c(1, 2, 3, 4, 5, 8), 6, 7)

我想根据它们属于列表元素的类别对数据框 id 列中的每个值进行分组,最好使用 purrr 包函数。所以所需的输出是这样的:

grp <- c(1, 1, 1, 1, 1, 2, 3, 1)

提前非常感谢你们,向你们学习/在你们身边学习是我一生的荣幸。

此致

Anoushiravan

案例-I 当列表未命名时

df <- structure(list(user_id = c(101, 102, 102, 103, 103, 106, 107,
                           111), phone_number = c(4030201, 4030201, 4030202, 4030202, 4030203,
                                                  4030204, 4030205, 4030203), id = 1:8), class = "data.frame", row.names = c(NA,
                                                                                                                             -8L))
lst <- list(c(1, 2, 3, 4, 5, 8), 6, 7)
library(tidyverse)

df %>% mutate(GRP = map(id, \(xy) seq_along(lst)[map_lgl(lst, ~ xy %in% .x)]))
#>   user_id phone_number id GRP
#> 1     101      4030201  1   1
#> 2     102      4030201  2   1
#> 3     102      4030202  3   1
#> 4     103      4030202  4   1
#> 5     103      4030203  5   1
#> 6     106      4030204  6   2
#> 7     107      4030205  7   3
#> 8     111      4030203  8   1

案例二当列表被命名时

df <- structure(list(user_id = c(101, 102, 102, 103, 103, 106, 107,
                           111), phone_number = c(4030201, 4030201, 4030202, 4030202, 4030203,
                                                  4030204, 4030205, 4030203), id = 1:8), class = "data.frame", row.names = c(NA,
                                                                                                                             -8L))
lst <- list(a = c(1, 2, 3, 4, 5, 8), b = 6, c = 7)

library(tidyverse)

df %>% mutate(GRP = map(id, \(xy) names(lst)[map_lgl(lst, ~ xy %in% .x)]))
#>   user_id phone_number id GRP
#> 1     101      4030201  1   a
#> 2     102      4030201  2   a
#> 3     102      4030202  3   a
#> 4     103      4030202  4   a
#> 5     103      4030203  5   a
#> 6     106      4030204  6   b
#> 7     107      4030205  7   c
#> 8     111      4030203  8   a

reprex package (v2.0.0)

于 2021 年 6 月 14 日创建

涉及 purrr 的一个选项可能是:

df %>%
    mutate(grp = imap(lst, ~ .y * (id %in% .x)) %>% reduce(`+`))

  user_id phone_number id grp
1     101      4030201  1   1
2     102      4030201  2   1
3     102      4030202  3   1
4     103      4030202  4   1
5     103      4030203  5   1
6     106      4030204  6   2
7     107      4030205  7   3
8     111      4030203  8   1