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

Carlo :

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?

Rui Barradas :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=367802&siteId=1