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!
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.
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.
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.
setdiff(x,y)
Will do the job for you.
> x[!x %in% y] [1] "b" "f"
or:
> x[-match(y,x)] [1] "b" "f" >
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