假设您的数据是这样的
test <- structure(list(items = list(c('a', 'b'), c('b', 'c', 'd'), c('d', 'e'), c('f', 'g', 'i'), c('g', 'h')),
ID = 1:5), row.names = c(NA, 5L), class = "data.frame")
test
items ID
1 a, b 1
2 b, c, d 2
3 d, e 3
4 f, g, i 4
5 g, h 5
as_tibble(test)
# A tibble: 5 x 2
items ID
<list> <int>
1 <chr [2]> 1
2 <chr [3]> 2
3 <chr [2]> 3
4 <chr [3]> 4
5 <chr [2]> 5
然后你可以做这样的事情
as_tibble(test) %>% mutate(combs = map(items, ~combn(.x, 2)))
# A tibble: 5 x 3
items ID combs
<list> <int> <list>
1 <chr [2]> 1 <chr[,1] [2 x 1]>
2 <chr [3]> 2 <chr[,3] [2 x 3]>
3 <chr [2]> 3 <chr[,1] [2 x 1]>
4 <chr [3]> 4 <chr[,3] [2 x 3]>
5 <chr [2]> 5 <chr[,1] [2 x 1]>
查看
as_tibble(test) %>% mutate(combs = map(items, ~combn(.x, 2))) %>%
data.frame()
items ID combs
1 a, b 1 a, b
2 b, c, d 2 b, c, b, d, c, d
3 d, e 3 d, e
4 f, g, i 4 f, g, f, i, g, i
5 g, h 5 g, h
或者
as_tibble(test) %>% mutate(combs = map(items, ~combn(.x, 2, list)))
# A tibble: 5 x 3
items ID combs
<list> <int> <list>
1 <chr [2]> 1 <list [1]>
2 <chr [3]> 2 <list [3]>
3 <chr [2]> 3 <list [1]>
4 <chr [3]> 4 <list [3]>
5 <chr [2]> 5 <list [1]>
取决于您想要的输入和输出格式