如何用R实现data frame中二进制变量组合的可扩展计数
a+b 2
a+c 0
a+d 0
a+e 0
a+f 1
a+b+c 0
a+b+d 0
a+b+e 1
a+b+f 0
a+c+d 1
a+c+e 0
...
a+b+c+d+e 1
...
a+b+c+d+e+f 1
...
# 解决方案 核心逻辑是:先将每个个体的特征转换为对应的组合字符串,再生成所有可能的特征组合,最后统计每个组合的出现次数(未出现的组合补0)。以下是基于`tidyverse`的实现方案: ## 方法一:全tidyverse流程 ```r library(tidyverse) # 1. 提取特征列名(排除id列) feature_cols <- names(example_data)[-1] # 2. 生成每个个体的特征组合字符串(过滤无特征的个体) individual_combs <- example_data %>% rowwise() %>% mutate( combination = paste0(feature_cols[c_across(all_of(feature_cols)) == 1], collapse = "+") ) %>% pull(combination) %>% discard(~ .x == "") # 若需要保留"无特征"的组合,删除此行 # 3. 生成所有可能的非空特征组合 all_possible_combs <- map(1:length(feature_cols), function(k) { combn(feature_cols, k, paste0, collapse = "+") }) %>% unlist() # 4. 统计次数并补全所有组合的计数 combination_counts <- tibble(combination = individual_combs) %>% count(combination, name = "count") %>% right_join(tibble(combination = all_possible_combs), by = "combination") %>% mutate(count = replace_na(count, 0)) %>% arrange(str_length(combination), combination) # 按组合长度+字母顺序排序
方法二:结合base R简化
如果觉得map+combn的写法繁琐,也可以用base R生成所有组合,再用tidyverse完成统计:
library(tidyverse) feature_cols <- names(example_data)[-1] # 生成所有非空特征组合 all_combs <- unlist(lapply(seq_along(feature_cols), function(k) { apply(combn(feature_cols, k), 2, paste, collapse = "+") })) # 统计并补全计数 combination_counts <- example_data %>% rowwise() %>% mutate(comb = paste(feature_cols[c_across(-id) == 1], collapse = "+")) %>% filter(comb != "") %>% # 若需要保留"无特征"组合,删除此行 count(comb) %>% right_join(tibble(combination = all_combs), by = c("comb" = "combination")) %>% rename(combination = comb) %>% mutate(count = replace_na(count, 0)) %>% arrange(str_length(combination), combination)
关键说明
- 代码支持任意数量的特征列,无需手动编码组合,完全可扩展
- 如果需要统计“无任何特征”的个体,只需移除代码中过滤空字符串的行即可
- 最终结果按组合长度(单个特征→多特征)和字母顺序排序,与示例输出格式一致
内容的提问来源于stack exchange,提问作者vengefulsealion
相关产品推荐
相关产品推荐

