r - 在数据框 R/组合学中寻找可行的组合

标签 r combinations combinatorics

我面临以下挑战: 包含 218 个观测值(行)和 218 个变量(列)的数据框。 这些值为 TRUE 或 FALSE。 现在我需要找到至少 2 行中出现 (TRUE) 的变量 (cols) 组合。

这是一个小例子:

data <- data.frame(matrix(FALSE, nrow = 3, ncol = 5))
colnames(data) = paste("item_", 1:5, sep = "")
rownames(data) = paste("Process_", 1:3, sep = "")
data["Process_1",c("item_1","item_2","item_3")] = TRUE
data["Process_2",c("item_2","item_3")] = TRUE
data["Process_3",c("item_1","item_2","item_3","item_4","item_5")] = TRUE

对于该示例,可行的组合(或找出的目标)是以下组合:

c1: 项目1,项目2,项目3

c2:项目2,项目3

c3:项目1,项目2

c4:项目1,项目3

非常感谢您的回答或提示:)

干杯

最佳答案

#all items that have TRUE in 2 or more rows
items <- names(which(colSums(data) >= 2))
# all possible combinations of 2 (or more) items
lapply(2:length(items), function(x) combn(items, x)
# [[1]]
#          [,1]     [,2]     [,3]    
# [1,] "item_1" "item_1" "item_2"
# [2,] "item_2" "item_3" "item_3"
# 
# [[2]]
#          [,1]    
# [1,] "item_1"
# [2,] "item_2"
# [3,] "item_3"

关于r - 在数据框 R/组合学中寻找可行的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71780173/

相关文章:

python - 组合学 - 安排比赛的团队协会

javascript - 随机 1-5 5x5 阵列

r - 基于多个条件创建输出

r - 删除重复的行,选择要保留的特定值

r - 按正则表达式模式选择列名

c - 如何生成长度恰好等于 8 的所有标记的集合

r - 图例与来自不同数据帧的多个图的交互作用 : How does one deal with this interaction?

javascript - 如何为两个数组的内容创建所有可能的组合?

matlab - Matlab 中集合的所有可能组合

algorithm - 如何找到给定字符串及其等级的排列?