一些样本数据:
n <- 10
dat <- data.frame(A = sample(0:1, n, replace = TRUE),
B = sample(0:1, n, replace = TRUE),
C = sample(0:1, n, replace = TRUE),
D = sample(0:1, n, replace = TRUE))
一个给定要组合的列数的函数,计算所有组合和相应的总和:
count.or <- function(dat, n = 2) {
or.sum <- function(cols) sum(rowSums(dat[cols]) > 0)
counts <- combn(colnames(dat), n, FUN = or.sum)
names <- combn(colnames(dat), n, FUN = paste, collapse = "")
setNames(counts, names)
}
在行动:
count.or(dat, 1)
# A B C D
# 6 6 5 9
count.or(dat, 2)
# AB AC AD BC BD CD
# 8 7 9 9 10 9
count.or(dat, 3)
# ABC ABD ACD BCD
# 9 10 9 10
count.or(dat, 4)
# ABCD
# 10
或一通电话:
unlist(lapply(1:4, count.or, dat = dat))
# A B C D AB AC AD BC BD CD ABC ABD ACD BCD ABCD
# 6 6 5 9 8 7 9 9 10 9 9 10 9 10 10