将组合变量combn解嵌套为向量

问题描述

使用以下代码,我设法获得了罚款 combination :

tibble(
    x = list(c(1,2,3),c(4,5,6))
  ) %>% 
  mutate(
      combination = 
        x %>% 
        map(
            .f = combn,2
          ) %>% 
        map(.f = t)
    ) %>% 
  unnest(combination)

# A tibble: 6 x 2
  x         combination[,1]  [,2]
  <list>              <dbl> <dbl>
1 <dbl [3]>               1     2
2 <dbl [3]>               1     3
3 <dbl [3]>               2     3
4 <dbl [3]>               4     5
5 <dbl [3]>               4     6
6 <dbl [3]>               5     6

但是,当使用 View() 函数观察时,我得到:

enter image description here

如何才能将 combination 显示为矢量?即:

enter image description here

解决方法

我们可以在 extend 中指定 simplify = FALSE 来返回一个 combn 而不是强制到 list

matrix

现在,执行library(purrr) library(dplyr) library(tidyr) tbl1 <- tibble( x = list(c(1,2,3),c(4,5,6)) ) %>% mutate( combination = x %>% map( .f = combn,simplify = FALSE ))

unnest

检查 out <- tbl1 %>% unnest(combination) out # A tibble: 6 x 2 # x combination # <list> <list> #1 <dbl [3]> <dbl [2]> #2 <dbl [3]> <dbl [2]> #3 <dbl [3]> <dbl [2]> #4 <dbl [3]> <dbl [2]> #5 <dbl [3]> <dbl [2]> #6 <dbl [3]> <dbl [2]>

enter image description here

,

这里有一个可能有帮助的 data.table 选项

library(data.table)
library(tidyr)
unnest(setDT(df)[,combination := lapply(x,function(v) combn(v,simplify = FALSE))],combination)