如何计算一组二元变量中至少2个变量取1的组合的出现频率
R统计二元变量组合出现频率方案
直接运行以下代码即可得到你需要的统计结果,核心逻辑是逐行提取取值为1的变量,生成所有长度≥2的变量组合后汇总计数:
依赖tidyverse的实现(代码更简洁)
# 构造示例数据 a <- c(0,1,0,1,0) b <- c(1,1,0,1,0) c <- c(0,1,0,0,0) df <- data.frame(a, b, c) # 加载依赖包 library(tidyverse) # 统计计算 result <- df %>% pmap_dfr(function(...) { current_row <- c(...) # 提取当前行取值为1的变量名 vars_with_1 <- names(current_row)[current_row == 1] if (length(vars_with_1) < 2) return(tibble(combinations = character())) # 生成所有长度≥2的组合 map_dfr(2:length(vars_with_1), function(k) { comb_items <- combn(vars_with_1, k, simplify = FALSE) tibble(combinations = map_chr(comb_items, paste0, collapse = "")) }) }) %>% # 统计各组合出现频次 count(combinations, name = "freq") # 输出结果 print(result)
运行输出如下:
combinations freq 1 ab 2 2 abc 1 3 ac 1 4 bc 1
基础R实现(无需额外安装包)
# 构造示例数据 a <- c(0,1,0,1,0) b <- c(1,1,0,1,0) c <- c(0,1,0,0,0) df <- data.frame(a, b, c) comb_collect <- c() for (i in 1:nrow(df)) { row_vals <- unlist(df[i, ]) vars_with_1 <- names(row_vals)[row_vals == 1] var_count <- length(vars_with_1) if (var_count < 2) next # 遍历所有符合要求的组合长度 for (k in 2:var_count) { current_combs <- combn(vars_with_1, k, simplify = FALSE) comb_str <- sapply(current_combs, paste0, collapse = "") comb_collect <- c(comb_collect, comb_str) } } result <- as.data.frame(table(comb_collect)) colnames(result) <- c("combinations", "freq") # 输出结果 print(result)
内容的提问来源于stack exchange,提问作者Sascha
相关产品推荐
相关产品推荐

