简体   繁体   中英

Compare two character vectors matching names

I have two character vectors with the different set of names and values:

x <- c("a", "b", "c", "d", "e")
names(x) <- c("foo", "bar", "baz", "qux", "grault")

y <- c("c", "a", "d", "b")
names(y) <- c("bar", "foo", "qux", "corge")

Is there a way to compare x and y so that we know their values corresponding to the name bar are different because here x.bar = "b" and y.bar = "c" ? Please note the names are not ordered. I tried setdiff and which(x != y) but neither one gives me the correct answer. Thanks!

你可以这样做:

x[intersect(names(x), names(y))] == y[intersect(names(x), names(y))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM