r - 将所有可能组合的矩阵转换为另一种格式
问题描述
我想创建一个向量的幂集矩阵。类似于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)
解决方案
在这里,我们可以得到combn
以返回指定为 'a'table
的factor
转换x
的,内部然后外部返回 a 。将二进制输出更改为“。” 和 'x' 代表 0 和 1levels
rbind
list
list
matrix
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
推荐阅读
- python - 在 numpy 中复制火炬标准化
- symfony - Symfony 4.4 带有 phpunit 急切加载集合的单元测试
- image-processing - 如何显示有关图像的所有元数据?
- django - 未找到“password_reset”的反向。'password_reset' 不是有效的视图函数或模式名称
- encryption - 使用 PROC Groovy 的 AES - SAS CI
- sonarqube - SonarQube.Analysis.xml 被忽略
- selenium - Groovy,通过 span 或 div 查找对象
- dataframe - 如何解决pyspark数据帧中的编码问题
- java - HttpUrlConnection 超时问题适用于本地主机,但在使用远程 IP 时它不起作用
- visual-studio-code - F# Codelens 语言环境