2

使用以下代码,我设法得到了罚款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(),我得到:

在此处输入图像描述

如何继续combination显示为矢量?IE :

在此处输入图像描述

4

2 回答 2

3

我们可以指定simplify = FALSEincombn来返回 alist而不是强制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
      , 2, 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]>  

检查View

在此处输入图像描述

于 2021-01-01T21:29:07.767 回答
1

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

library(data.table)
library(tidyr)
unnest(setDT(df)[, combination := lapply(x, function(v) combn(v, 2, simplify = FALSE))], combination)
于 2021-01-01T22:29:06.950 回答