0

I am trying to check if all the elements inside a vector are the same. I am using this code:

if( isTRUE(for(i in 1:length(x)){x[1]==x[i]})){print(x[1])} else{print("several")

Now suppose

x <- c(0,0,0,0,0,0,0,0,0,0,0) 

Here, the code should return "0" and if

x <- c(0,0,0,0,0,1,0,0,0,0,0) 

it should return "several". In both cases I get "several", any idea why is not working as desired? Thank u in advance.

Cettt
  • 11,460
  • 7
  • 35
  • 58
mimus
  • 53
  • 5
  • Do you need `any(x != 0)` – akrun Apr 03 '19 at 14:54
  • Where does `testpos[1]` come from? Also check out this question for better alternatives: https://stackoverflow.com/questions/4752275/test-for-equality-among-all-elements-of-a-single-vector. A "for" loop in R doesn't return any values. – MrFlick Apr 03 '19 at 14:54
  • srry editing testpos should be x – mimus Apr 03 '19 at 14:55

1 Answers1

2

there is a simpler way:

if (length(unique(x)) == 1) {
  print(x[1])
} else {
  print("several")
}

If you want to compare all components of x with the first component you should use all instead of a for loop:

if (all(x == x[1])) {
  print(x[1])
} else {
  print("several")
}

The result of both approaches is the same.

Cettt
  • 11,460
  • 7
  • 35
  • 58