Vivek Subramanian - 1 year ago 97
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

`a`
such as
`a[[1]]`
,
`a[[2]]`
, 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
`x`
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
`a[[10]]`
currently equals
`[3 3 1]`
and, in a new
`x`
(which somehow corresponds to the tenth entry in
`a`
), I count
`[1 0 1]`
, I'd like
`a[[10]]`
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
`x`
corresponding to
`a[[10]]`
unless I've pre-allocated the matrix entry to contain 0's.

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))`.