[R] Counting unique items in a list of matrices

Peter Ehlers ehlers at ucalgary.ca
Sat Oct 9 18:44:44 CEST 2010


On 2010-10-07 10:10, Jim Silverton wrote:
> Hello,
> I gave  a list of 2 x 2 matrices called matlist. I have about 5000 2 x 2
> matrices. I would like to count how many of each 2 x 2 unique matrix I have.
> So I am thinking that I need a list of the unique 2 x 2 matrices and their
> counts. Can anyone help.
>

Here's one way, using the plyr package:

  require(plyr)
  ## make a list of 2X2 matrices
  L <- vector('list', 5000)
  set.seed(4321)
  for(i in 1:5000) L[[i]] <- matrix(round(runif(4), 1), 2, 2)

  ## convert each matrix to a string of 4 numbers, then
  ## form dataframe
  dL <- ldply(L, function(.x) toString(unlist(.x)))

  ## add an index vector
  dL$ind <- seq_len(5000)

  ## count unique strings; return string, frequency, indeces
  result <- ddply(dL, .(V1), summarize,
                               freq=length(V1),
                               idx=toString(ind))


    -Peter Ehlers



More information about the R-help mailing list