Ofelia Pan
Ofelia Pan

Reputation: 11

Missing value where TRUE/FALSE needed in min function

Question 1. Write a function called my_min() that computes the minimum of a numeric vector without the min() function. Include a logical argument called na.rm that specifies whether to remove NAs.

my_min <- function(x){
  for (i in 1:length(x)) {
      if (x[i] < x[i+1]) {
        result <- x[i]
      } else {
        result <- x[i+1]
      }
  }
result
}

my_min(1:10)

Error in if (x[i] < x[i + 1]) { : missing value where TRUE/FALSE needed

I don't know why there is a missing value; can someone teach me how to do it with an if statement? (even if it does not need it, I just want to know the correct way to answer this question with an if statement).

Upvotes: 0

Views: 812

Answers (1)

Rajith Thennakoon
Rajith Thennakoon

Reputation: 4130

Try this

my_min <- function(x){
  min <- x[1]
  for (i in 1:(length(x)-1)) {
    now <- x[i+1]
    is.rm <- is.na(now)
    if ((now < min) & !is.rm) {
       min <- now
    } 
  }
  min
}

Upvotes: 0

Related Questions