I am trying to create a function in R that searches in strings a specific pattern in a specific position, if the letter is present in the established position, I want to count it.
example of dataset:
library(dplyr)
mutations <- tibble(
"position" = c(9,10),
"AA" = c("G","G"))
strings <- c("EVQLVESGGGLAKPG",
"VQLVESGGGLAKPGGS",
"EVQLVESGGALAKPGGSLRLSCAAS")
So, in this case, I want to look for the position 9 and 10, if there is a letter "G" I want to count it.
Expected dataframe or tibble output:
| string | mut_counts |
|________|____________|
| 1 | 2 |
|________|____________|
| 2 | 1 |
|________|____________|
| 3 | 1 |
|________|____________|
In this example, all strings have a "G" at position 9, so they would all get 1, and only one of the three sequences have a "G" at position 10, so this sequence will have 2.
I am trying to use str_locate_all() from the stringr package to be able to locate the positions and then compare with my dataframe to count but I am failing to get what I wanted.
library(stringr)
.class_mutations <- function(sequences, mutations){
.count_pattern <- function(x){
df <- sum(as.integer(locating_all_patterns[[x]][,"start"] == mutations$position[mut]))
}
for(mut in nrow(mutations)){
locating_all_patterns <- str_locate_all(pattern = mutations$AA[mut], sequences)
counting_patterns <- lapply(locating_all_patterns, .count_pattern)
}
return(counting_patterns)
}
.class_mutations(strings, mutations)
I am getting this error Error in locating_all_patterns[[x]] : no such index at level 1, besides, if you have a better/faster way to do this, I would also appreciate it. I have to take into account that this is going to applied in thousands of strings, so I should avoid slow functions.
Thank you