How can I check if a vector has all the same elements?
For example let's say I have:
vec1 = rep(10,20)
vec2 = seq(1:20)
How can I show that vec1
has all the same elements?
Check if Two Objects are Equal in R Programming – setequal() Function. 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.
Method 2: Using length() and unique() function By using unique function if all the elements are the same then the length is 1 so by this way if the length is 1, we can say all elements in a vector are equal.
First of all, create a number of vectors. Use intersect function to find the common elements in all the vectors.
An option is diff
.
diff(vec1)
If the elements are equal, their difference is zero.
all(diff(vec1) == 0)
#[1] TRUE
Or compare the vector to its first element.
all(vec1 == vec1[1])
#[1] TRUE
Several ways of determining if all elements of a vector are equal were posted, see RHertel, Yuriy Saraykin, tmfmnk. Here are comparative tests.
library(microbenchmark)
library(ggplot2)
f <- function(n){
x <- rep(10, n)
mb <- microbenchmark(
var = var(x) == 0,
sd = sd(x) == 0,
diff = all(diff(x) == 0),
extract = all(x == x[1]),
unique = length(unique(x)) == 1
)
mb
}
sizes <- c(10, 100, seq(1e3, 1e4, by = 1e3))
mb_list <- lapply(sizes, f)
names(mb_list) <- sizes
res <- lapply(seq_along(mb_list), function(i){
agg <- aggregate(time ~ expr, mb_list[[i]], median)
agg$size <- sizes[i]
agg
})
res <- do.call(rbind, res)
ggplot(res, aes(size, time, colour = expr)) +
geom_point() +
geom_line()
Use the variance. If all elements of a vector are equal, the variance is zero:
allElementsEqual <- function(x) {!var(x)}
#allElementsEqual(vec1)
#[1] TRUE
#allElementsEqual(vec2)
#[1] FALSE
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