# Re: [R] Newbie: Matrix indexing

From: Gabor Grothendieck <ggrothendieck_at_myway.com>
Date: Wed 23 Mar 2005 - 00:35:52 EST

Pascal BLEUYARD <p.bleuyard <at> opgc.univ-bpclermont.fr> writes:

:
: Hi all,
:
: I need to compute some "occurence matrix": given a zero matrix and a set
: of paired indexes, I want to store the number of occurences of each paired
: index in a matrix. The paired indexes are stores as an index matrix. I
: prefere not to use loops for performances purpose.
:
: Here follows a dummy example:
:
: > occurence <- matrix(0, 2, 2); data
: [,1] [,2]
: [1,] 0 0
: [2,] 0 0
: >
: > index <- matrix(1, 3, 2); index
: [,1] [,2]
: [1,] 1 1
: [2,] 1 1
: [3,] 1 1
: >
: > occurence[index] <- occurence[index] + 1
:
: I was expecting the folowing result:
:
: > occurence
: [,1] [,2]
: [1,] 3 0
: [2,] 0 0
:
:
: > occurence
: [,1] [,2]
: [1,] 1 0
: [2,] 0 0
:
: I guess that there is some "hidden copy" involved but I wanted to know if
: there is an efficient workaround (not using some loop structure). I thought
: "factors" could do the job but I didn't manage to use them for that problem.

Turn your index matrix into a data frame so you can use lapply on it. Then convert each of the two columns to a two-level factor. Now you can use table on the result:

table(lapply(as.data.frame(index), factor, lev = 1:2))

R-help@stat.math.ethz.ch mailing list