nickolakis
nickolakis

Reputation: 621

Check if a data frame contains at least one zero value inside an if statement in R

I have a dataframe in R as follows

df <-
  as.data.frame(cbind(c(1,2,3,4,5), c(0,1,2,3,4,5),c(1,2,4,5,6)))

and I have a function in which I want the procedure to stop and display a message if the input df contains at least one 0 value. I tried the following but can't make it work properly. What is the correct if() statement I should use?

my_function <- function(df){

  if (all(df == 0) == 'TRUE')
    stop(paste("invalid input df"))
}

Upvotes: 1

Views: 75

Answers (1)

akrun
akrun

Reputation: 887108

We could use %in%

my_function <- function(df) {
     if(0 %in% unlist(df)) {
       stop("invalid input df")
     }
}

Upvotes: 1

Related Questions