Simon
Simon

Reputation: 349

Check if rows of matrix are all the same

m1 = matrix(c(2,1,4,3,5,6),ncol=3)
m2 = matrix(c(1,2,3,4,6,5),ncol=3)
m1==m2

I need to show that m1=m2 because their rows are the same. Any way to do it?

Upvotes: 2

Views: 602

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101508

You can use setdiff() to make it, where you treat rows as sets and calculate their difference, i.e.,

length(setdiff(data.frame(t(m1)),data.frame(t(m2))))==0

such that

> length(setdiff(data.frame(t(m1)),data.frame(t(m2))))==0
[1] TRUE

Upvotes: 2

akrun
akrun

Reputation: 887148

If we need a single TRUE/FALSE as output, use either all.equal or identical after ordering the row of one of the dataset (or both - if both are not ordered. In this example, 'm2' is already ordered)

all.equal( m1[do.call(order, as.data.frame(m1)),], m2)

If it should return TRUE/FALSE for each row, create a condition with rowSums

rowSums(m1[do.call(order, as.data.frame(m1)),] == m2) == ncol(m2) 

Upvotes: 1

Related Questions