From a dataframe I get a new array, sliced from a dataframe.
I want to get the amount of times a certain repetition appears on it.
For example
main <- c(A,B,C,A,B,V,A,B,C,D,E)
p <- c(A,B,C)
q <- c(A,B)
someFunction(main,p)
2
someFunction(main,q)
3
I’ve been messing around with rle but it counts every subrepetion also, undersirable.
Is there a quick solution I’m missing?
You can use one of the regular expression tools in R since this is really a pattern matching exercise, specifically
gregexprfor this question. Thepandqvectors represent the search pattern andmainis where we want to search for those patterns. From the help page forgregexpr:So we can take the length of the first list returned by
gregexprwhich gives the starting positions of the matches. We’ll first collapse the vectors and then do the searching:Note – you also need to throw “” around your vector
main,p, andqvectors unless you have variables A, B, C, et al defined.