Case-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
Case-II当列表命名时
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-06-14 创建