Is there an efficient way to check whether an R character vector contains the same elements?

  • A+

Let's say I have an R vector of type character:

vector1 = c("dog", "cat", "fish") vector2 = c("fish", "fish", "fish") 

The first vector vector1 contains three distinct elements: dog, cat, fish

However, vector2 contains all the same elements.

I'm looking for an efficient way to check this property in an R vector, preferably using base R.

My idea would be to use the following:

Check length(unique(vector1))==1. If TRUE, then there's only 1 element. If FALSE, there are many.

Alternatively, you can use all.

> all(vector1 == vector1[1]) [1] FALSE > all(vector2 == vector2[1]) [1] TRUE 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: