Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two character vectors matching names

Tags:

r

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!

like image 321
Rock Avatar asked Oct 18 '12 15:10

Rock


People also ask

How do you compare two vectors?

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.

Which function will compare two sets of vectors to see if the vectors share the same characters?

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.

How do I compare two lists of elements in R?

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.


1 Answers

You could do this:

x[intersect(names(x), names(y))] == y[intersect(names(x), names(y))]
like image 97
Matthew Plourde Avatar answered Sep 25 '22 08:09

Matthew Plourde