Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing character vectors in R to find unique and/or missing values

Tags:

I have two character vectors, x and y.

x <- c("a", "b", "c", "d", "e", "f", "g") y <- c("a",      "c", "d", "e",      "g") 

The values inside x do not ever repeat (i.e., they are all unique). The same goes for vector y. My question is, how can I get R to compare the two vectors, and then tell me which elements are missing from y with respect to x? Otherwise stated, I want R to tell me that "b" and "f" are missing from y.

(Note, in my real data, x and y each contain a few thousand observations, which is why I would like to do this programmatically. There is likely a very simple answer, but I wasn't sure what to search for in the R help files).

Thanks to anyone who can help!

like image 633
Alexander Avatar asked Feb 06 '12 15:02

Alexander


People also ask

How do I find unique values in a vector in R?

Use the unique() function to retrieve unique elements from a Vector, data frame, or array-like R object. The unique() function in R returns a vector, data frame, or array-like object with duplicate elements and rows deleted.

How do you compare two vectors the same in R?

setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not.

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.


2 Answers

setdiff(x,y) 

Will do the job for you.

like image 84
saudic Avatar answered Oct 13 '22 21:10

saudic


> x[!x %in% y] [1] "b" "f" 

or:

> x[-match(y,x)] [1] "b" "f" >  
like image 42
Justin Avatar answered Oct 13 '22 22:10

Justin