Home > front end >  How to validate if all elements in a vector equal to a scalar in R?
How to validate if all elements in a vector equal to a scalar in R?

Time:06-06

lets assume we have this vector:

v <- c(1,1,1,1,1)

Is there a function that validates if all elements in a vector are equal to a scallar?

In other words v == 1 returns TRUE ?

CodePudding user response:

I think you can use all ?

all(c(1, 1, 1, 1, 1) == 1)
[1] TRUE

all(c(1, 1, 1, 1, 2) == 1)
[1] FALSE

CodePudding user response:

You could use min() and max():

v <- c(1,1,1,1,1)
max(v) == 1 && min(v) == 1

[1] TRUE

The logic here is that if the smallest and largest values in the incoming vector are both 1, then all values must 1.

  • Related