I have 9 gene lists, each 2000 genes in length. I want to keep genes if present in 6 or more of lists. I am not sure how to specify this, I have been using the intersect function.
Any help is appreciated.
I have 9 gene lists, each 2000 genes in length. I want to keep genes if present in 6 or more of lists. I am not sure how to specify this, I have been using the intersect function.
Any help is appreciated.
First, recreate the data with a little helper function:
# gene generating function as a trigram of lower case letters
gene <- function(...) {
paste(sample(letters, 3), collapse = "")
}
# creating lists of genes
gene_lists <- lapply(seq(9), function(x) sapply(seq(2000), gene))
Then extracts the unique elements:
# getting unique genes
unique_genes <- unique(unlist(gene_lists))
length(unique_genes)
[1] 10661
Here we can check that the synthetic data have some redundancy:
# checking if there are enough redundant genes
stopifnot(length(unique_genes) < length(unlist(gene_lists)))
Then iterate over unique gene and list while counting occurences:
# iterating over unique_genes
gene_occurence <- sapply(unique_genes, function(gene) {
# iterating over lists
# sum counts the total number of occurence
sum(sapply(gene_lists, function(x) { gene %in% x }))
})
length(gene_occurence)
[1] 10661
table(gene_occurence)
1 2 3 4 5 6
6017 3330 1050 231 31 2
Then get the common genes:
limit <- 6
common_genes <- unique_genes[which(gene_occurence >= limit)]
common_genes
[1] "ngu" "het"