Vivek Subramanian Vivek Subramanian - 10 months ago 72
R Question

Matrix of empty tables in R

I'm trying to count the number of occurrences in many vectors and store them in a matrix in R. For example, I'd like entries in the matrix

such as
, etc. to contain counts of the number of 7's, 8's, and 9's in a set of vectors. I know I can produce the counts using
table(factor(x, levels=7:9))
, where
is one of the vectors in the set, but I'd like to pre-allocate the matrix with empty tables because I have to sometimes add on to the previous table that already exists in one of the matrix entries. For example if
currently equals
[3 3 1]
and, in a new
(which somehow corresponds to the tenth entry in
), I count
[1 0 1]
, I'd like
to be updated to
[4 3 2]
. This can be done in one line by just adding the new counts to the previous value, but I can't do this the first time I count in an
corresponding to
unless I've pre-allocated the matrix entry to contain 0's.

Answer Source

I did this simply by preceding my code with a check for if a[[i]] is null. If so, then I did a[[i]] = table(factor(0, levels=7:9)).