samedi 27 avril 2019

R function with two arguments if statement

I am trying to write a function which takes in two arguments, and produces two results. The first function needs to compare an integer to 100, and provide "invalid" for text. This the code for that:

   compare <- function(x) {

   if (!is.numeric(x))  {
   result = "invalid" 
   }
   else if (x>100) {
   result = "Pass"
   }

   else if (x<100) {
   result = "Fail"
   }

   else if (x==100) {
   result = "Neutral"
   }

   print(result)

   }

The second function needs to prints "valid" if a character/text, and provide nothing if an integer.

   compare2 <- function(y) {

   if (!is.numeric(y))  {
   result = "valid" 
   }

   else if (!is.numeric(y)) {
   result = ""
   }

   print(result)

   } 

My question is how to I combine these two functions into one? I've tried multiple things (not shown), but nothing seems to work. I need one function, called compare for example, which has two arguments like so:

 compare <- function(x,y) {....
 }

My problem is that I don't know how to combine the two arguments into one function block. The output should look like this:

 compare(10,"text") ===> "fail","valid"
 compare(100, 90) ===> "neutral"
 compare("text","text") ==> "invalid","valid"

Aucun commentaire:

Enregistrer un commentaire