tabulateworks with whole vectors and works fast; match your letters with universes of possible letters, and then insert an index into the table; use length(a)to make sure there is one counter for each possible value.
> tabulate(match(b, a), length(a))
[1] 1 2 0 0 0
This is faster than the "obvious" solution to table ()
library(microbenchmark)
f0 = function() table(factor(b,levels=a))
f1 = function() tabulate(match(b, a), length(a))
and then
> microbenchmark(f0(), f1())
Unit: microseconds
expr min lq median uq max neval
f0() 566.824 576.2985 582.950 594.4200 798.275 100
f1() 56.816 60.0180 63.305 65.4185 120.441 100
but also more general, for example, matching numeric values without resorting to string representation.
source
share