[R] Counting unique items in a list of matrices

Jeffrey Spies jspies at virginia.edu
Sat Oct 9 19:23:35 CEST 2010


If you just want a list of matrices and their counts, you can use
Peter's list of matrices, L, and then:

With plyr:

require(plyr)
count(unlist(lapply(L, toString)))

Without plyr:

as.data.frame(table(unlist(lapply(L, toString))))

Cheers,

Jeff.

On Sat, Oct 9, 2010 at 12:44 PM, Peter Ehlers <ehlers at ucalgary.ca> wrote:
> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list