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

Time:09-07

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"))
}

CodePudding user response:

We could use %in%

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