[R] Is there a quick way to count the number of times each element in a vector appears?

Dylan Arena darena at stanford.edu
Tue Mar 6 07:16:57 CET 2007


Hi there,


I'm writing a function that calculates the probability of different
outcomes of dice rolls (e.g., the sum of the highest three rolls of
five six-sided dice).  I'm using the "combinations" function from the
"gtools" package, which is great: it gives me a matrix with all of the
possible combinations (with repetitions allowed).  Now I want to count
the number of times each element appears in each arrangement so I can
calculate the number of permutations of that arrangement.  E.g., if I
get output like:

> combinations(3,3, rep=TRUE)
      [,1] [,2] [,3]
 [1,]    1    1    1
 [2,]    1    1    2
 [3,]    1    1    3
 [4,]    1    2    2
 [5,]    1    2    3
 [6,]    1    3    3
 [7,]    2    2    2
 [8,]    2    2    3
 [9,]    2    3    3
[10,]    3    3    3

I'd like to be able to determine that the first row has 3 repetitions,
yielding 3!/3! = 1 permutation, while the second row has 3
repetitions, yielding 3!/2! = 3 permutations, etc.  (This gets harder
when there are large numbers of dice with many faces.)

I know there are simple things to do, like iterating over the rows
with for loops, but I've heard that for loops are sub-optimal in R,
and I'd like to see what an elegant solution would look like.

E.g., I might like to use sapply() with whatever function I come up
with; I thought of using something like duplicated() and just counting
the number of TRUEs that are returned for each vector (since the
elements are always returned in non-decreasing order), but I'm
optimistic that there is a better (faster/cleaner) way.

So here is my question in a nutshell:
Does anyone have ideas for how I might efficiently process a matrix
like that returned by a call to combinations(n, r, rep=TRUE) to
determine the number of repetitions of each element in each row of the
matrix?  If so, I'd love to hear them!


Thanks very much for your time,
Dylan Arena
(Statistics M.S. student)



More information about the R-help mailing list