如何将 combn() 函数应用于列表类型的列?

问题描述

我有一个包含 3 列的数据框,其中一列是列表类型

>head(basket_data)
# A tibble: 8 x 3
  order_id items      count
     <int> <list>     <int>
1        2 <chr [9]>      9
2        3 <chr [8]>      8
3        4 <chr [13]>    13
4        5 <chr [26]>    26
5        6 <chr [3]>      3

对于第 1 行 (order_id 2),列表为 [a,b,c]

我想使用 combn 函数(也许?)创建一个新列,它将仅包含该行的列表的所有对组合,因此 [[a,b],[b,c],[a,c ]]

我在 SO 上遇到的所有使用 combn 的示例都组合了数据框中的每个列表并将整个列表配对。任何帮助,将不胜感激。谢谢!

解决方法

假设您的数据是这样的

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,2))) %>%
  data.frame()
    items ID            combs
1    a,b  1             a,b
2 b,d  2 b,b,d,d
3    d,e  3             d,e
4 f,i  4 f,f,i,i
5    g,h  5             g,h

as_tibble(test) %>% mutate(combs = map(items,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]>

取决于你想要的输入和输出格式

,

这里尝试使用 dplyrpurrr 以及使用您的共享示例随机生成的一些示例数据。

library(dplyr)
library(purrr)

set.seed(10)
basket_data <- tibble(
  order_id = seq(2,6,by = 1),items = lapply(floor(runif(5,5,20)),FUN = function(x) { sample(letters,size = x) }),count = floor(runif(5,1,30))
)

basket_data$new_col <- map(basket_data$items,.f = function(x) combn(x,FUN = function(x) list(x)))

basket_data
#> # A tibble: 5 x 4
#>   order_id items      count new_col     
#>      <dbl> <list>     <dbl> <list>      
#> 1        2 <chr [12]>    24 <list [66]> 
#> 2        3 <chr [9]>      8 <list [36]> 
#> 3        4 <chr [11]>     5 <list [55]> 
#> 4        5 <chr [15]>     5 <list [105]>
#> 5        6 <chr [6]>     15 <list [15]>

部分结果示例

# Here is first items list
basket_data$items[[1]]
#>  [1] "w" "h" "v" "g" "s" "o" "u" "j" "z" "x" "b" "y"

# Here is some example of new_col for first items
basket_data$new_col[[1]][1:10]
#> [[1]]
#> [1] "w" "h"
#> 
#> [[2]]
#> [1] "w" "v"
#> 
#> [[3]]
#> [1] "w" "g"
#> 
#> [[4]]
#> [1] "w" "s"
#> 
#> [[5]]
#> [1] "w" "o"
#> 
#> [[6]]
#> [1] "w" "u"
#> 
#> [[7]]
#> [1] "w" "j"
#> 
#> [[8]]
#> [1] "w" "z"
#> 
#> [[9]]
#> [1] "w" "x"
#> 
#> [[10]]
#> [1] "w" "b"

reprex package (v2.0.0) 于 2021 年 5 月 18 日创建