How to know if a vector is composed by the same elements?

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

Edit.

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()

enter image description here


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

Tags:

Unique

R

Vector