Sergei
Sergei

Reputation: 1637

Use identical() ignoring order of items in list

I am playing with indentical function and I have found out that this comparison will return false:

identical(list(z = c(1,1,1), q = c(0,0,0)), list(q = c(0,0,0), z = c(1,1,1)))

Is there a way to make sure that the order of q and z does not matter, so the answer will be True?

Upvotes: 3

Views: 1680

Answers (1)

MrFlick
MrFlick

Reputation: 206187

Well, if you have

a <- list(z = c(1,1,1), q = c(0,0,0))
b <- list(q = c(0,0,0), z = c(1,1,1))
identical(a,b)
# [1] FALSE

they are not identical because

a[[1]]
# [1] 1 1 1
b[[1]]
# [1] 0 0 0
identical(a[[1]], b[[1]])
# [1] FALSE

which means that the list will behave differently in certain situations.

If you want to compare regardless of order, you can sort the lists by name

identical(a[order(names(a))], b[order(names(b))])
# [1] TRUE

Upvotes: 6

Related Questions