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!
A vector quantity has two characteristics, a magnitude and a direction. When comparing two vector quantities of the same type, you have to compare both the magnitude and the direction. On this slide we show three examples in which two vectors are being compared. Vectors are usually denoted on figures by an arrow.
intersect() function is used to return the common element present in two vectors. Thus, the two vectors are compared, and if a common element exists it is displayed.
Compare equal elements in two R lists Third, you can also compare the equal items of two lists with %in% operator or with the compare. list function of the useful library. The result will be a logical vector.
You could do this:
x[intersect(names(x), names(y))] == y[intersect(names(x), names(y))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With