Without an example, I cannot be sure that I understand what you want. However, I think you want something similar. If so, there are almost certainly better ways to do the same.
a <- matrix(c(1,2, 3,4, 5,6, 7,8), nrow=4, byrow=T, dimnames = list(NULL, c("x","y"))) b <- matrix(c(1,2, 9,4, 9,6, 7,9), nrow=4, byrow=T, dimnames = list(NULL, c("x","y"))) cc <- matrix(c(NA,NA, NA,NA, NA,NA, NA,NA), nrow=4, byrow=T, dimnames = list(NULL, c("x","y"))) for(i in 1:dim(a)[1]) { for(j in 1:dim(a)[2]) { if(a[i,j]==b[i,j]) cc[i,j]=a[i,j] } } cc
EDIT: January 8, 2013
The next line tells you which cells differ between the two matrices:
which(a != b, arr.ind=TRUE)
If the two matrices a and b are identical, then:
which(a != b)
EDIT January 9, 2012
The following code demonstrates the impact that row names can have on identical
, all.equal
and which
, when one of the two data frames is created by a subset of the third data frame. If the row names differ between the two compared data frames, neither identical
nor all.equal
returns TRUE
. However, which
can still be used to compare columns x
and y
between two data frames. If the row names are set to NULL
for each of the two compared data frames, then both identical
and all.equal
will return TRUE
.
df1 <- read.table(text = " group xy 1 10 20 1 10 20 1 10 20 1 10 20 2 1 2 2 3 4 2 5 6 2 7 8 ", sep = "", header = TRUE) df2 <- read.table(text = " group xy 2 1 2 2 3 4 2 5 6 2 7 8 ", sep = "", header = TRUE)