首页 > 解决方案 > 将所有可能组合的矩阵转换为另一种格式

问题描述

我想创建一个向量的幂集矩阵。类似于SO 上的这个问题

我有这个

#data
a <- c("test1","test2","test3")

#result
data.table::rbindlist(
    sapply(1:3, function(i) as.data.frame(t(combn(a, i)))), fill = TRUE)
#>       V1    V2    V3
#> 1: test1  <NA>  <NA>
#> 2: test2  <NA>  <NA>
#> 3: test3  <NA>  <NA>
#> 4: test1 test2  <NA>
#> 5: test1 test3  <NA>
#> 6: test2 test3  <NA>
#> 7: test1 test2 test3

reprex 包于 2021-04-14 创建(v1.0.0)

我想把它改成这个(如果可能的话,我也不想要这些点):

library(tidyr)
#> Warning: replacing previous import 'vctrs::data_frame' by 'tibble::data_frame'
#> when loading 'dplyr'
tribble(
    ~test1, ~test2, ~ test3,
    "x", ".", ".",
    ".", "x", ".",
    ".", ".", "x",
    "x", "x", ".",
    "x", ".", "x",
    ".", "x", "x",
    "x", "x", "x"
)
#> # A tibble: 7 x 3
#>   test1 test2 test3
#>   <chr> <chr> <chr>
#> 1 x     .     .    
#> 2 .     x     .    
#> 3 .     .     x    
#> 4 x     x     .    
#> 5 x     .     x    
#> 6 .     x     x    
#> 7 x     x     x

reprex 包于 2021-04-14 创建(v1.0.0)

标签: r

解决方案


在这里,我们可以得到combn以返回指定为 'a'tablefactor转换x的,内部然后外部返回 a 。将二进制输出更改为“。” 和 'x' 代表 0 和 1levelsrbindlistlistmatrix

out <- do.call(rbind, lapply(1:3, function(i) 
    do.call(rbind, combn(a, i, FUN = function(x)
      table(factor(x, levels = a)), simplify = FALSE))))

out[] <- c('.', 'x')[1 + out]
as.data.frame(out)
#   test1 test2 test3
#1     x     .     .
#2     .     x     .
#3     .     .     x
#4     x     x     .
#5     x     .     x
#6     .     x     x
#7     x     x     x

推荐阅读