mardi 30 octobre 2018

R tryCatch with three possible outcomes

I'm currently working with a tryCatch within a custom function that will output a string. The tryCatch querys a database with a set of parameters to see if there is enough data, it subsequently checks to see if two columns also have enough unique values. I want there to be three different outcomes, a 'success', 'not enough data', and 'SQL error' (while also printing the SQL error). There are 3 places where it should return 'not enough data'. Currently my code works for both the success and error, but I cannot seem to get it to output 'not enough data', in the case where it should be 'not enough data' I get an error return. Any ideas as to why it is happening this way?

custfunct <- function(query_string,connect_string){
out<-tryCatch(
    {

      connection <- odbcDriverConnect(connect_string)
      initdata<- sqlQuery(connection,query_string)
      print(initdata)
      # Check if query has returned an error. print the error
      if (is.character(initdata))
        {
        print <- paste(initdata, collapse = "\n")
      }
      return ("error")

      if (nrow(initdata) >5)
      {

        print("rows more than five")
        if (length(unique(initdata$column_1)) >5)
        {

          print('unique column 1 more than 5')
          if (length(unique(initdata$column_2) >5)
          {

            print("unique column 2 more than 5")
          }

          return("success")
        }

        else
        {
          print("There are too few samples")

          return("not enough data")
        }

      }

      else
      {

        print("Either there is no data or too few samples")

        return("not enough data")
      }
    },
    error=function(errorvalue){
     return("error")
    }
    ,finally={
    }
  )
  return(out)
}

Aucun commentaire:

Enregistrer un commentaire