Use all() or any() to reduce your comparison to a single logical value. In your case all(S == P) appears to be what you intended, although maybe not what you wanted (see the next para). Also check out ?identical and the comments in ?"==" (which BTW contains the answer to your question).
On 24 Jan 2004, Federico Calboli wrote:
Dear All, how can I get a logical comparison between matrices (or vectors) in a if statement? Whenever I try I get the following:
S<-rbind(c(.25,0,0),c(0,.2,0),c(0,0,.1))
P<-rbind(c(.75,.15,.01),c(.2,.8,.09),c(.05,.05,.9))
aa<-function(S,P){
+ if (S == P){
+ return("OK")
+ }
+ else {
+ return("No match")
+ }
+ }
aa(S,P)
[1] "No match"
Warning message:
the condition has length > 1 and only the first element will be used in:
if (S == P) {
The warning clearly states that only the first element was used, and
this would not be good enough.
If comparing the whole matrices is not possible I could be happy just
comparing the two diagonals.
regards,
Federico Calboli
Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595