# [SOLVED] How to write a function in to a ifelse formula in R?

## Issue

I have two functions:

``````METAL <- function(x){
between(x, 241,259)|
between(x,271,309)
}

MOTOR <- function(x){
x == 452|
x == 454)
}
``````

I would like to use the function as a condition in an ifelse formula.

``````DF\$SUB <- ifelse(DF\$IND == METAL(DF\$IND), "Metal", "Other")

DF\$SUB <- ifelse(DF\$IND == MOTOR(DF\$IND), "Motor", DF\$SUB)

``````

It lables every row as "Other". Even rows where IND == 241 and should be labled as "Metal".

IND contains numbers from 10 to 999

I want to add a new column named SUB to the DF and write in to column "Metal" where column IND is the same as defined in the function METAL, write "Motor" where it is defined as MOTOR and "Other" in all other rows.

How do i put the function in to the ifelse correctly? I need it as a function so that if i change the parameters it will be changed everywhere in code not just one place.

Thank you

## Solution

Your functions are returning logicals, no need to compare them to IND column anymore.

``````#example data
DF <- data.frame(IND = c(240:243, 260, 451, 452, 454, 455))

METAL <- function(x) between(x, 241, 259) | between(x, 271, 309)
MOTOR <- function(x) x == 452 | x == 454

DF\$SUB <- ifelse(METAL(DF\$IND), "Metal",
ifelse(MOTOR(DF\$IND), "Motor", "Other"))

DF
#   IND   SUB
# 1 240 Other
# 2 241 Metal
# 3 242 Metal
# 4 243 Metal
# 5 260 Other
# 6 451 Other
# 7 452 Motor
# 8 454 Motor
# 9 455 Other
``````