Brian
Brian

Reputation: 3

Error in ifelse unused argument(3) in a function in R programming

tod = function(x) { 
  ifelse(x > 5 && x < 12, 1, ifelse( x > 16 && x < 20, 2, 3), 3)
}
df2$day = tod(df2$t)

Error in ifelse(x > 5 && x < 12, 1, ifelse(x > 16 && x < 20, 2, 3), 3): unused argument (3)

Upvotes: 0

Views: 146

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521168

You are nesting your ifelse calls incorrectly, but to avoid this completely you might want to look into using case_when from the dplyr package:

tod = function(x) {
    case_when(
        x > 5 && x < 12  ~ 1,
        x > 16 && x < 20 ~ 2,
        TRUE             ~ 3
    )
}

Upvotes: 1

Lennyy
Lennyy

Reputation: 6132

ifelse(x > 5 && x < 12, 1, ifelse( x > 16 && x < 20, 2, 3))

You first ifelse expects 3 arguments. 1st: x > 5 && x < 12 2nd: 1 3rd: ifelse( x > 16 && x < 20, 2, 3)

With , 3 you gave a 4th argument to your first ifelse(), which caused the error

Upvotes: 0

Related Questions