微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决将组合变量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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。