Reputation: 1769
I have the following sentences:
sentences1<-c("The color blue neutralizes orange yellow reflections.",
"Zod stabbed me with blue Kryptonite.",
"The color blue neutralizes orange yellow reflections.",
"Red is wrong, blue is right.",
"Red is wrong, blue is right.",
"Red is wrong, blue is right.",
"You ruined my beautiful green dress.",
"There's nothing wrong with green.")
and
sentences2<-c("Red is wrong, blue is right.",
"Red is wrong, blue is right.",
"Red is wrong, blue is right.")
How can I check if all the sentences contained in sentences1
and sentences2
are equal to each other? For example, in sentences1
we have not the same sentences while sentences2
contains the same.
Upvotes: 1
Views: 38
Reputation: 9865
equals_vec <- function(vec) if (length(vec) <= 1) {TRUE} else if (vec[1] == vec[2]) {equals_vec(vec[2:length(vec)])} else {FALSE}
equals_vec(sentences1) # FALSE
equals_vec(sentences2) # TRUE
# in contrast to `unique` it stops at first appearance of unequal element
# in the vec it walks through
Upvotes: 1
Reputation: 388962
You can count the number of unique values in the vector.
is_unique <- function(x) {
length(unique(x)) == 1
#dplyr::n_distinct(x) == 1
}
is_unique(sentences1)
#[1] FALSE
is_unique(sentences2)
#[1] TRUE
Upvotes: 1
Reputation: 39657
You can use all
and compare the first [1]
with the rest [-1]
.
all(sentences1[1] == sentences1[-1])
#[1] FALSE
all(sentences2[1] == sentences2[-1])
#[1] TRUE
Upvotes: 2