mimus
mimus

Reputation: 53

R, problems using a for cycle inside if else

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.

Upvotes: 0

Views: 57

Answers (1)

Cettt
Cettt

Reputation: 11981

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.

Upvotes: 2

Related Questions