Test Match and Order between two vectors in R

拟墨画扇 提交于 2019-12-24 08:49:04

问题


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.


回答1:


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')
}


来源:https://stackoverflow.com/questions/23392963/test-match-and-order-between-two-vectors-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!