Re: [R] another matrix question

From: Julien Barnier <>
Date: Mon, 21 Apr 2008 14:18:11 +0200


> Given matrix m and matrix n, I would like to compute mn[i,,j]= m[i,,j]
> + n[i,,j] if either of these elements is 0. (In other words, whichever
> number is nonzero.)
> Else I want mn[i,,j]=(m[i,,j] + n[i,,j])/2
> I need a fast method.

m <- matrix(c(0,1,2,3,4,0,5,6,0),nrow=3,ncol=3) n <- matrix(c(1,2,0,3,0,4,0,5,6),nrow=3,ncol=3)

mn <- ifelse(m==0 | n==0, m+n,(m+n)/2)

Hope that helps,

Julien Barnier
Groupe de recherche sur la socialisation
ENS-LSH - Lyon, France

______________________________________________ mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.
Received on Mon 21 Apr 2008 - 12:41:55 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 22 Apr 2008 - 05:30:30 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive