سؤال

I would like to test the match and order between two vectors. I'm aware of the match function; are there overlays to assess the order simultaneously? For example:

x <- c("a", "b", "c")
y <- c("b", "a", "c")   
x %in% y    

There are perfect matches, but the ordering is not correct. Thoughts on how to identify that? Thanks.

هل كانت مفيدة؟

المحلول

test_match_order <- function(x,y) {

if (all(x==y)) print('Perfect match in same order')

if (!all(x==y) && all(sort(x)==sort(y))) print('Perfect match in wrong order')

if (!all(x==y) && !all(sort(x)==sort(y))) print('No match')
}

test_match_order(x,y)

[1] "Perfect match in wrong order"

And here is another version based on my original comment above with an improvement from @alexis_laz below that makes the function more robust:

test_match_order2 <- function(x,y) {

if (isTRUE(all.equal(x,y))) print('Perfect match in same order')

if (!isTRUE(all.equal(x,y)) && isTRUE(all.equal(sort(x),sort(y)))) print('Perfect match in wrong order')

if (!isTRUE(all.equal(x,y)) && !isTRUE(all.equal(sort(x),sort(y)))) print('No match')
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top