Search code examples
rmin

How to use min when all values are missing?


I am looking to save the minimum values of a series of columns like this:

  x1 x2 x3
  2  1  4 
  1  NA 3
  NA NA NA

using code like this

min_val <- min(x1, x2, x3, na.rm=TRUE)

and I want to get this back

  1
  1
  NA

but I keep getting an infinite loop. I've included some example code down below. How can I get it to tell me that the third row is NA instead of failing to execute?

Thanks!

  x1 <- c(1,2,NA)
  x2 <- c(2,NA,NA)
  x3 <- c(3,5,NA)

  test <- cbind(x1, x2, x3)
  head(test)

  for (i in 1:nrow(test)){
    min_val[i] <- min(test[i,], na.rm = TRUE)
  }
  head(min_val)

Solution

  • How about this:

    min_val <- function(x) {
     apply(x, 1, function(x) if(all(is.na(x))) {NA} else {min(x, na.rm = T)}) 
    }
    
    min_val(test)
    [1]  1  2 NA