# [R] matching values in a list

Gabor Grothendieck ggrothendieck at gmail.com
Sat Jan 12 01:23:24 CET 2008

Assume that no component matrix can have repeated values.

First we apply table to mat yielding a list of named counts.
To each component of that we sapply the indicated function
which picks out those that occur length(a) times (so they are
in every column), converts the name to numeric and averages
them.

sapply(apply(mat, 2, table), function(x) mean(as.numeric(names(x))[x
== length(a)]))

By the way, note that the a you define is slightly different from the

On Jan 11, 2008 6:09 PM, dxc13 <dxc13 at health.state.ny.us> wrote:
>
> useR's,
>
> I want to match the real number elements of a list that has 3 matrices as
> its elements and then average those numbers.  I think I am close, but I
> can't get it to quite work out.  For example,
>
> > a <- list(matrix(c(10,NA,NA,12,11,
> > 10,13,NA,14,12),ncol=2),matrix(c(10,12,15,13,11,
> > 13,NA,NA,12,10),ncol=2),matrix(c(10,15,NA,13,NA, 13,12,NA,NA,10),ncol=2))
> > a
> [[1]]
>     [,1] [,2]
> [1,]   10   10
> [2,]   NA   13
> [3,]   NA   NA
> [4,]   13   14
> [5,]   11   12
>
> [[2]]
>     [,1] [,2]
> [1,]   10   13
> [2,]   12   NA
> [3,]   15   NA
> [4,]   13   12
> [5,]   11   10
>
> [[3]]
>     [,1] [,2]
> [1,]   10   13
> [2,]   15   12
> [3,]   NA   NA
> [4,]   13   NA
> [5,]   NA   10
>
> I want to average the non-NA numbers that simultaneously appear in each
> column of all 3 matrices.  For the first column, 10 and 13 are the only
> numbers that appear in all 3 matrices.  Thus, I want to take the average of
> 10 and 13.  Then repeat the same process for the second column.  The data
> here is only a sample, but with the data I work with, there are many more
> columns in each matrix in the list.  Does anyone know a efficient way to do
> this?  Maybe using lapply()?  Thanks in advance.
>
> dxc13
> --
> View this message in context: http://www.nabble.com/matching-values-in-a-list-tp14767170p14767170.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help