Marco Dinatsoli
Marco Dinatsoli

Reputation: 10580

all() function is not working as expected

I have a vector and I want to be sure that all its values are between 1800 and 900

All the values are integer.

I did this:

areThereOutRangedTimeValues <- function (time){
  valuesGreaterThan <- time > 1800
  if(all(valuesGreaterThan) == FALSE){
  valuesLessThan <- time< 900
  if(all(valuesLessThan) == FALSE){
    return (FALSE)
  }
  else
  {
    return (TRUE)
  }
  }else{
    return (TRUE)
  }
}

I don't know why when I test it like this:

areThereOutRangedTimeValues(c(1:1801))

The answer is FALSE, even though it should have been TRUE.

Upvotes: 1

Views: 67

Answers (2)

Pierre L
Pierre L

Reputation: 28451

Building on the answer by nico. If you want a function:

OutRanged <- function(time) {
  any(time < 900 | time > 1800)
}

OutRanged(1:1801)
[1] TRUE

You can also make it more useful by being able to change the range if wanted.

OutRanged <- function(time, lower=900, upper=1800) {
  any(time < lower | time > upper)
}

So now you can still do the same test:

OutRanged(1:1801)
[1] TRUE

Or you can add a different upper or lower bound to the range:

OutRanged(1:1801, 0, 1801)
[1] FALSE

Upvotes: 1

nico
nico

Reputation: 51670

The issue is

all(valuesGreaterThan) == FALSE

which should really be (note the parentheses)

all(valuesGreaterThan == FALSE)

Same for valuesLessThan

However, this seems like a very involved way of doing

any(time<900 | time>1800)

Upvotes: 6

Related Questions