この単純なワンライナーはbase r
、strsplit、次にgreplを使用し、かなり堅牢ですがjjjjjj
、3ロットのように一致をカウントする必要がある場合は壊れますjj
。これを可能にするパターンマッチは、@ JoshOBriensの優れたQ&Aからのものです。
sum( grepl( "jj" , unlist(strsplit( x , "(?<=.)(?=jj)" , perl = TRUE) ) ) )
# Examples....
f<- function(x){
sum( grepl( "jj" , unlist(strsplit( x , "(?<=.)(?=jj)" , perl = TRUE) ) ) )
}
#3 matches here
xOP <- c("ajjss","acdjfkj","auyjyjjksjj")
f(xOP)
# [1] 3
#4 here
x1 <- c("ajjss","acdjfkj", "jj" , "auyjyjjksjj")
f(x1)
# [1] 4
#8 here
x2 <- c("jjbjj" , "ajjss","acdjfkj", "jj" , "auyjyjjksjj" , "jjbjj")
f(x2)
# [1] 8
#Doesn't work yet with multiple jjjj matches. We want this to also be 8
x3 <- c("jjjj" , "ajjss","acdjfkj", "jj" , "auyjyjjksjj" , "jjbjj")
f(x3)
# [1] 7