I am slightly new to writing functions in R. Here I have a basic function that searches for a pattern and returns the indexes of where the occurence occurs given a list dataset
#this functions takes a pattern and prints the indexes for the matches
find_domain <- function(pattern,list) grep(pattern,list,ignore.case=T)
Sometimes during the analysis i found that i need to do that for a larger dataset. The idea is to look for occurence of a domain (pattern) in each of the d7_dataset rows(since each row represents a protein sequence and each column is a domain) such that i can then count the number of sequences that contain or have a given domain(pattern in this case) So i wrote this
seqs <- c()
for (i in 1:nrow(d7_dataset)){
pos <- find_domain("CIDRγ13",d7_dataset[i,])
if (!is.na(pos[1]))
seqs <- c(seqs,1)
}
total_seqs <- sum(seqs)
total_seqs
However this seems like it can be written as a single function so that i can eliminate duplication and simplify it such that it is generic enough to apply to multiple datasets. Any ideas on how to condence it to a single function? In a nutshell, Given a pattern or list of patterns and a dataset(as a dataframe) to search, return the number of sequences(rows in the dataset) that contain the given pattern.
More or less like this
results <– search(a list of patterns to search,dataset)
results should look like
pattern count
pat1 40
pat2 3
pat3 0
. .
. .
It would be very good if the pattern argument would accept a list to search
Thank you
find_domain
if the only thing it does it's callinggrep
. You are just adding the overhead of another function call. $\endgroup$