简体   繁体   English

R中满足一定条件的列组合

[英]Combinations of columns that meet a certain condition in R

I am fairly new to R and I would appreciate any help I get.我对 R 相当陌生,如果能得到任何帮助,我将不胜感激。 I have the following binary table:我有以下二进制表:

example <- matrix(ncol=4,c(1,1,0,1,1,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0))
colnames(example) <- c("c1","c2","c3","c4")
rownames(example) <- c("r1","r2","r3","r4","r5")

I would like to get all possible combinations of columns where all rows have a "1".我想获得所有行都有“1”的所有可能的列组合。 In this example, I would get the following output:在这个例子中,我会得到以下 output:

result = ((c1,c3),(c2,c1,c3),(c2,c1,c4),(c3,c1,c4),(c3,c1,c4,c2),(c4,c1))结果 = ((c1,c3),(c2,c1,c3),(c2,c1,c4),(c3,c1,c4),(c3,c1,c4,c2),(c4,c1))

Once again thank you for all the help.再次感谢您的所有帮助。 Cheers干杯

This needs some work, but thought I would throw this out there.这需要一些工作,但我想我会把它扔在那里。 I know others in SO can improve upon this (significantly, I might add).我知道 SO 中的其他人可以改进这一点(重要的是,我可能会补充)。 I would be very open to comments and improving this answer if I can.如果可以的话,我会非常愿意接受评论并改进这个答案。

First would get all combinations of column names, with varying lengths (vary from 1 to 4 columns), and put into a list.首先将获取列名的所有组合,具有不同的长度(从 1 到 4 列不等),并放入一个列表中。

lst <- do.call(c, lapply(seq_along(colnames(example)), combn, x = colnames(example), simplify = FALSE))

Second, would go through that list, and create matrices for those selected columns.其次,将 go 通过该列表,并为那些选定的列创建矩阵。

lst2 <- lapply(lst, function(x) matrix(example[,x], ncol = length(x)))

Third, would name the list based on the column names and remove the quotes.第三,将根据列名命名列表并删除引号。

names(lst2) <- gsub('[\"]', '', lst)

Fourth, would check each matrix in the list where (a) any column in a row has a 1, and (b) all rows meet criteria (a).第四,将检查列表中的每个矩阵,其中 (a) 行中的任何列都有 1,并且 (b) 所有行都符合标准 (a)。

names(which(lapply(lst2, function(x) { all(apply(x, 1, function(y) any(y > 0))) } ) == TRUE))

Output Output

[1] "c(c1, c3)"         "c(c1, c4)"         "c(c1, c2, c3)"     "c(c1, c2, c4)"     "c(c1, c3, c4)"    
[6] "c(c1, c2, c3, c4)"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM