Reputation: 11
I am fairly new to R and I would appreciate any help I get. 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". In this example, I would get the following output:
result = ((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
Upvotes: 1
Views: 237
Reputation: 30474
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). 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.
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.
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).
names(which(lapply(lst2, function(x) { all(apply(x, 1, function(y) any(y > 0))) } ) == TRUE))
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)"
Upvotes: 2