Leo.peis
Leo.peis

Reputation: 14323

Extracting only some rows of a table in R

I have a table in this format:

fragment of  table

I am trying to write a R script that will "extract" from the table for example the cases that have c2==1, (c2 and c3)== 1, (c2 and c4)==1, (c1 and c2 and c3)==1, and so on ... so that in the end I will have a list that has the Counts value for each case.

Example list for columns that have c2 == 1: C2<-c(4, 42, 12, ...)

I tried to it on this way: totalC2<-table[table[c1]], also if I use table$c1 == 1 it is not working.

Can anyone give-me a suggestion how to solve this problem?

I forgot to mention that the table comes from the function: vennCounts()

Upvotes: 0

Views: 2747

Answers (1)

DrDom
DrDom

Reputation: 4123

In the output you will have named list with corresponding counts. But maybe the same results could be achieved with the more clear and straightforward solution. Let's wait and see for another answers.

# data simulation
c1 <- sample(c(0,1), 10, replace=T)
c2 <- sample(c(0,1), 10, replace=T)
c3 <- sample(c(0,1), 10, replace=T)
c4 <- sample(c(0,1), 10, replace=T)
Counts <- sample(1:100, 10)
df <- data.frame(c1, c2,c3, c4, Counts)

f <- function(y) {
  idx <- apply(df[,y, drop=F], 1, function(x) all(x == 1))
  df[idx, "Counts"]
}

out <- list()
l <- sapply(1:4, function(x) {combn(x=c("c1", "c2", "c3", "c4"), m=x, simplify=F)})
l <- unlist(l, recursive=F)
for (x in l) {
  out[[paste(x, collapse="")]] <- f(x)
}

Upvotes: 1

Related Questions