Unnesting a combination variable (combn) as a vector

Viewed 66

With the following code, I manage to get a fine 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

Howerver, when observed with the View() function, I get :

enter image description here

How can I proceed to get combination displayed as a vector? i.e. :

enter image description here

2 Answers

We can specify the simplify = FALSE in combn to return a list instead of coercing to 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
      )) 

Now, do the 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]>  

check the View

enter image description here

Here is a data.table option that might help

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