Регулярные выражения стоят дорого. Вы можете получить результат в своем вопросе с точным сравнением.
> somechars <- sample(LETTERS, 5e6, TRUE)
> sum(c(somechars=="A",somechars=="B"))
[1] 385675
> system.time(sum(c(somechars=="A",somechars=="B")))
user system elapsed
0.416 0.072 0.487
ОБНОВЛЕНО, чтобы включить время из OP и другие ответы. Также включен тест, превышающий 2-символьный регистр.
> library(rbenchmark)
> benchmark( replications=5, order="relative",
+ grep = sum(grepl("A|B",somechars)),
+ table = sum(table(somechars)[c("A","B")]),
+ c = sum(c(somechars=="A",somechars=="B")),
+ OR = sum(somechars=="A"|somechars=="B"),
+ IN = sum(somechars %in% c("A","B")),
+ plus = sum(somechars=="A")+sum(somechars=="B") )
test replications elapsed relative user.self sys.self user.child sys.child
6 plus 5 4.289 1.000000 3.836 0.436 0 0
3 c 5 4.991 1.163675 4.156 0.804 0 0
5 IN 5 5.480 1.277687 4.549 0.880 0 0
4 OR 5 5.574 1.299604 5.000 0.544 0 0
1 grep 5 16.426 3.829797 16.205 0.172 0 0
2 table 5 17.834 4.158079 12.793 4.884 0 0
>
> benchmark( replications=5, order="relative",
+ grep = sum(grepl("A|B|C|D",somechars)),
+ table = sum(table(somechars)[c("A","B","C","D")]),
+ c = sum(c(somechars=="A",somechars=="B",
+ somechars=="C",somechars=="D")),
+ OR = sum(somechars=="A"|somechars=="B"|
+ somechars=="C"|somechars=="D"),
+ IN = sum(somechars %in% c("A","B","C","D")),
+ plus = sum(somechars=="A")+sum(somechars=="B")+
+ sum(somechars=="C")+sum(somechars=="D") )
test replications elapsed relative user.self sys.self user.child sys.child
5 IN 5 5.513 1.000000 4.464 1.004 0 0
6 plus 5 8.603 1.560493 7.705 0.860 0 0
3 c 5 10.283 1.865228 8.648 1.560 0 0
4 OR 5 12.348 2.239797 10.849 1.464 0 0
2 table 5 17.960 3.257754 12.877 4.921 0 0
1 grep 5 21.692 3.934700 21.405 0.192 0 0