Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If Statement Returning Number Instead of Variable Name

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Is there a way to do this?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading