0

I am trying to make a function in which I have to provide two arguments. For the first argument, I can enter anything, but for the second only the characters 'A' or 'B' are allowed. Then I wish to return both arguments in a list.

myFunction <- function(var1, var2){

  if(missing(var1) | var1 == ""){stop("First argument is missing")}
  if(missing(var2) | var2 != "A" | var2 != "B"){stop("Second argument is missing. Accepted values: 'A' or 'B'")}

  myList <- list("out1" = var1, "out2"=var2)
  return(myList)
}

myFunction("Hello world!", "A")
Error in myFunction("Hello world!", "A") : 
  Second argument is missing. Accepted values: 'A' or 'B'

What am I missing?

1
  • 2
    you need to have (var2 != "A" & var2 != "B") instead of the or in the var2 condition. (edit: see answer below) Commented Jun 2, 2020 at 15:25

1 Answer 1

2

It's your boolean logic.

var2 is missing = F
var2 != 'A' = F
var2 != 'B' = T

F or F or T evaluates to T

Sign up to request clarification or add additional context in comments.

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.