0

I'm trying to write an if statement in a function. It's for the x variable that either can be a couple of the variables from the dataset or all of the variables in the data.frame, like: (Both X and Y are given like column names)

f <- function(y,x,data){
    if (x=="all"){something<-y+2}else{something<-y+5}
}

I get the error:

"the condition has length > 1 and only the first element will be used"

2
  • 1
    Please provide a working example / sample data set. Commented May 28, 2016 at 1:44
  • That's usually the error you get when you need to use ifelse (which is vectorized) instead of if (which is not), but it's hard to say without data/context. Commented May 28, 2016 at 1:47

1 Answer 1

1

I would like to address how the logical comparison works. This may help you solve the problem.

If you use logical operation without if statement, you will get this.

c("a","b","c","a") == "a"
[1]  TRUE FALSE FALSE  TRUE

However, if you use the logical operation within "if" statement, it works differently. It uses only the first element like this example.

if(c("a","b","c","a") == "b"){print("exist")}else{print("not exist")}
[1] "not exist"

if(c("a","b","c","a") == "a"){print("exist")}else{print("not exist")}
[1] "exist"

I assume you may need to use length() or %in%.

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.