Home > Software design >  If Statement Returning Number Instead of Variable Name
If Statement Returning Number Instead of Variable Name

Time:10-16

I am working on this dummy problem in R:

Patient_Being_Tested_Disease = 0

Method_1 = 0.1

Method_4 = 0.4

Method_5 = 0.5

I am trying to write the following IF condition

winner = ifelse( Patient_Being_Tested_Disease == 0, min(Method_1, Method_4, Method_5), max(Method_1, Method_4, Method_5))

> winner
[1] 0.1

This works - but I instead of returning a number, I want to return either the "Method" corresponding to the number being returned.

For example, I would like the IF statement to return "Method_1" instead of 0.1 .

Is there a way to do this?

CodePudding user response:

An easy way to do what you want with the ifelse statement is to merge your values to a named character vector and then reconstruct the statement.

Patient_Being_Tested_Disease = 0

methods <- c(Method_1 = 0.1, 
             Method_2 = 0.4,
             Method_5 = 0.5)

ifelse(Patient_Being_Tested_Disease == 0, 
names(methods)[which.min(methods)],
names(methods)[which.max(methods)])

Output:

[1] "Method_1"

What this does is that now, the which.min/max functions target the name of the vector instead of the value itself.

  •  Tags:  
  • r
  • Related