For two logical vectors, x
and y
, of length > 1E8, what is the fastest way to calculate the 2x2 cross tabulations?
I suspect the answer is to write it in C/C++, but I wonder if there is something in R that is already quite smart about this problem, as it's not uncommon.
Example code, for 300M entries (feel free to let N = 1E8 if 3E8 is too big; I chose a total size just under 2.5GB (2.4GB). I targeted a density of 0.02, just to make it more interesting (one could use a sparse vector, if that helps, but type conversion can take time).
set.seed(0)
N = 3E8
p = 0.02
x = sample(c(TRUE, FALSE), N, prob = c(p, 1-p), replace = TRUE)
y = sample(c(TRUE, FALSE), N, prob = c(p, 1-p), replace = TRUE)
Some obvious methods:
table
bigtabulate
- Simple logical operations (e.g.
sum(x & y)
) - Vector multiplication (boo)
data.table
- Some of the above, with
parallel
from themulticore
package (or the newparallel
package)
I've taken a stab at the first three options (see my answer), but I feel that there must be something better and faster.
I find that table
works very slowly. bigtabulate
seems like overkill for a pair of logical vectors. Finally, doing the vanilla logical operations seems like a kludge, and it looks at each vector too many times (3X? 7X?), not to mention that it fills a lot of additional memory during processing, which is a massive time waster.
Vector multiplication is usually a bad idea, but when the vector is sparse, one may get an advantage out of storing it as such, and then using vector multiplication.
Feel free to vary N
and p
, if that will demonstrate anything interesting behavior of the tabulation functions. :)
Update 1. My first answer gives timings on three naive methods, which is the basis for believing table
is slow. Yet, the key thing to realize is that the "logical" method is grossly inefficient. Look at what it's doing:
- 4 logical vector operations
- 4 type conversions (logical to integer or FP - for
sum
) - 4 vector summations
- 8 assignments (1 for the logical operation, 1 for the summation)
Not only that, but it's not even compiled or parallelized. Yet, it still beats the pants off of table
. Notice that bigtabulate
, with an extra type conversion (1 * cbind...
) still beats table
.
Update 2. Lest anyone point out that logical vectors in R support NA
, and that that will be a wrench in the system for these cross tabulations (which is true in most cases), I should point out that my vectors come from is.na()
or is.finite()
. :) I've been debugging NA
and other non-finite values - they've been a headache for me recently. If you don't know whether or not all of your entries are NA
, you could test with any(is.na(yourVector))
- this would be wise before you adopt some of the ideas arising in this Q&A.
Update 3. Brandon Bertelsen asked a very reasonable question in the comments: why use so much data when a sub-sample (the initial set, after all, is a sample ;-)) might be adequate for the purposes of creating a cross-tabulation? Not to drift too far into statistics, but the data arises from cases where the TRUE
observations are very rare, for both variables. One is a result of a data anomaly, the other due to a possible bug in code (possible bug because we only see the computational result - think of variable x
as "Garbage In", and y
as "Garbage Out". AS a result, the question is whether the issues in the output caused by the code are solely those cases where the data is anomalous, or are there some other instances where good data goes bad? (This is why I asked a question about stopping when a NaN
, NA
, or Inf
is encountered.)
That also explains why my example has a low probability for TRUE
values; these really occur much less than 0.1% of the time.
Does this suggest a different solution path? Yes: it suggests that we may use two indices (i.e. the locations of TRUE
in each set) and count set intersections. I avoided set intersections because I was burned awhile back by Matlab (yes, this is R, but bear with me), which would first sort elements of a set before it does an intersection. (I vaguely recall the complexity was even more embarrassing: like O(n^2)
instead of O(n log n)
.)
If you're doing a lot of operations on huge logical vectors, take a look at the bit package. It saves a ton of memory by storing the booleans as true 1-bit booleans.
This doesn't help with
table
; it actually makes it worse because there are more unique values in the bit vector due to how it's constructed. But it really helps with logical comparisons.Here are results for the logical method,
table
, andbigtabulate
, for N = 3E8:In this case,
table
is a disaster.For comparison, here is N = 3E6:
At this point, it seems that writing one's own logical functions is best, even though that abuses
sum
, and examines each logical vector multiple times. I've not yet tried compiling the functions, but that should yield better results.Update 1 If we give
bigtabulate
values that are already integers, i.e. if we do the type conversion1 * cbind(v1,v2)
outside of bigtabulate, then the N=3E6 multiple is 1.80, instead of 2.4. The N=3E8 multiple relative to the "logical" method is only 1.21, instead of 1.53.Update 2
As Joshua Ulrich has pointed out, converting to bit vectors is a significant improvement - we're allocating and moving around a LOT less data: R's logical vectors consume 4 bytes per entry ("Why?", you may ask... Well, I don't know, but an answer may turn up here.), whereas a bit vector consumes, well, one bit, per entry - i.e. 1/32 as much data. So,
x
consumes 1.2e9 bytes, whilexb
(the bit version in the code below) consumes only 3.75e7 bytes.I've dropped
table
and thebigtabulate
variations from the updated benchmarks (N=3e8). Note thatlogicalB1
assumes that the data is already a bit vector, whilelogicalB2
is the same operation with the penalty for type conversion. As my logical vectors are the results of operations on other data, I don't have the benefit of starting off with a bit vector. Nonetheless, the penalty to be paid is relatively small. [The "logical3" series only performs 3 logical operations, and then does a subtraction. Since it's cross-tabulation, we know the total, as DWin has remarked.]We've now sped this up to taking only 1.8-2.8 seconds, even with many gross inefficiencies. There is no doubt it should be feasible to do this in well under 1 second, with changes including one or more of: C code, compilation, and multicore processing. After all the 3 (or 4) different logical operations could be done independently, even though that's still a waste of compute cycles.
The most similar of the best challengers,
logical3B2
, is about 80X faster thantable
. It's about 10X faster than the naive logical operation. And it still has a lot of room for improvement.Here is code to produce the above. NOTE I recommend commenting out some of the operations or vectors, unless you have a lot of RAM - the creation of
x
,x1
, andxb
, along with the correspondingy
objects, will take up a fair bit of memory.Also, note: I should have used
1L
as the integer multiplier forbigtabulate
, instead of just1
. At some point I will re-run with this change, and would recommend that change to anyone who uses thebigtabulate
approach.Here's an answer with
Rcpp
, tabulating only those entries that are not both0
. I suspect there must be several ways to improve this, as this is unusually slow; it's also my first attempt withRcpp
, so there may be some obvious inefficiencies associated with moving the data around. I wrote an example that is purposefully plain vanilla, which should let others demonstrate how this can be improved.Timing results for
N = 3E8
:This takes more than 6X as long as
func_find01B
in my 2nd answer.Here is an answer using Rcpp sugar.
which results in:
So, we can get a little speed up over the bit package, though I'm surprised at how competitive the times are.
Update: In honor of Iterator, here is a Rcpp iterator solution:
A different tactic is to consider just set intersections, using the indices of the
TRUE
values, taking advantage that the samples are very biased (i.e. mostlyFALSE
).To that end, I introduce
func_find01
and a translation that uses thebit
package (func_find01B
); all of the code that doesn't appear in the answer above is pasted below.I re-ran the full N=3e8 evaluation, except forgot to use
func_find01B
; I reran the faster methods against it, in a second pass.Just the "fast" methods:
So,
find01B
is fastest among methods that do not use pre-converted bit vectors, by a slim margin (2.099 seconds versus 2.327 seconds). Where didfind02
come from? I subsequently wrote a version that uses pre-computed bit vectors. This is now the fastest.In general, the running time of the "indices method" approach may be affected by the marginal & joint probabilities. I suspect that it would be especially competitive when the probabilities are even lower, but one has to know that a priori, or via a sub-sample.
Update 1. I've also timed Josh O'Brien's suggestion, using
tabulate()
instead oftable()
. The results, at 12 seconds elapsed, are about 2Xfind01
and about half ofbigtabulate2
. Now that the best methods are approaching 1 second, this is also relatively slow:Code: