Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

unique

vector

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?

like image 975
Carlo Avatar asked Mar 01 '20 16:03

Carlo


People also ask

How do you tell if two vectors are identical in R?

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.

How do you check that all elements of a vector are equal in R?

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.

How do you find the common element in two vectors in R?

First of all, create a number of vectors. Use intersect function to find the common elements in all the vectors.


2 Answers

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

like image 128
Rui Barradas Avatar answered Oct 20 '22 01:10

Rui Barradas


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
like image 34
RHertel Avatar answered Oct 20 '22 00:10

RHertel