R mean values of a sum of Matrices without divide for points equal zero

120 Views Asked by At

A = matrix(c(1,2,3, 0, 2, 2, 0,2 ,3), nrow=3, ncol=3)

[,1] [,2] [,3]
[1,]    1    0    0
[2,]    2    2    2
[3,]    3    2    3

B = matrix(c(1,2,3, 1, 4, 2, 2,2 ,1), nrow=3, ncol=3)

[,1] [,2] [,3]
[1,]    1    1    2
[2,]    2    4    2
[3,]    3    2    1

C = A + B /(Sum numbers diff of zero)

C = matrix(c(1,2,3, 1, 3, 2, 2,2 ,2), nrow=3, ncol=3)

    [,1] [,2] [,3]
[1,]    1    1    2
[2,]    2    3    2
[3,]    3    2    2

I need do it for a list of N matrices (mat_vect[[i]]):

list_mat_vect[[i]] <- assign(paste("a", i, sep = ""), mat_vect[[i]])

Sum matrix and get mean value

mat_sum_mean = Reduce("+", list_mat_vect) / length(file_list) 

Here is dividing for all numbers, including the zeros. I dont want that.

1

There are 1 best solutions below

0
On BEST ANSWER

You can do

(A+B)/((A!=0) + (B!=0))

to get

     [,1] [,2] [,3]
[1,]    1    1    2
[2,]    2    3    2
[3,]    3    2    2

Here != tests for equality with zero returning TRUE or FALSE. When we add those up, the TRUEs are treated like 1 and the FALSEs become 0.

You can do this with a list of matrices as well

list_mat_vect<-list(A,B)
Reduce("+", list_mat_vect) / Reduce("+", lapply(list_mat_vect, function(x) x!=0))