1

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"

2 Answers 2

2

Try this:

compare <- function(x,y) {
  if (!is.numeric(x))  {
    result = "invalid" 
  }
  else if (x>100) {
    result = "Pass"
  }

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

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

  if (!is.numeric(y))  {
    paste(result,'valid', sep = ", ", collapse = NULL)
  }

  else if (!is.numeric(y)) {
    paste(result,'', sep = "", collapse = NULL)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Something like this? Although I guess the desired output can be achieved in other ways as well.

compare <- function(x,y) {
result1=vector()

if (!is.numeric(x))  {
result1 <- c(result1,"valid")
}
else if (x>100) {
result1 <- c(result1,"Pass")
}

else if (x<100) {
result1 <- c(result1,"Fail")
}

else if (x==100) {
result1 <- c(result1,"Neutral")
}

 if (!is.numeric(y))  {
result1 <- c(result1,"valid")
}

 cat(paste(shQuote(result1, type="cmd"), collapse=", "))
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.