mardi 25 août 2015

Trouble with if-statement using any( ) and apply( )

Suppose that I have the following table of information:

firstname <- c('Todd','Sven','Robert','Jovan','Angelo')
city <- c('Edmond', NA ,'Miami','Houston', NA)
state <- c('OK','KS', NA, 'TX', NA)
job <- c('Clown','Plumber','Professor', 'Uber Driver', 'Therapist')

list_test <- data.frame(firstname, city, state, job)
list_test

  firstname    city state         job
1      Todd  Edmond    OK       Clown
2      Sven    <NA>    KS     Plumber
3    Robert   Miami  <NA>   Professor
4     Jovan Houston    TX Uber Driver
5    Angelo    <NA>  <NA>   Therapist

I want to return a message if any of the columns is NA, which can be identified by doing this:

any(apply(list_test, 2, function(x){any(is.na(x))}))
[1] TRUE

My thought is to create a simple if-return statement like below.

if(any(apply(list_test, 2, function(x){any(is.na(x))}))) {
  return("At least one row has an NA value.")
}

However, I get the following error message:

Error: no function to return from, jumping to top level

I am confused as to why I am getting this error message.

Thank you!

Aucun commentaire:

Enregistrer un commentaire