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

Using if to compare column values

Here’s my df, labeled "Task".

Country Confirmed Ratio
1 Austria 2510071 28.2
2 Bolivia 888175 7.8

I am required to use an if-else statement to do two things: (1) determine which value in the "Ratio" column is greater, and (2) create a new column that says either "Highest" or "Lowest" for the appropriate observation.

I’ve read dozens of posts about using if-else, but I cannot seem to find examples of a condition that says "see if the ‘Ratio’ value in this row is greater or lesser than the ‘Ratio’ value in another row". I’ve made lots of if() attempts, but they’ve all failed pretty miserably.

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

My goal is code that’ll produce this output:

Country Confirmed Ratio Rank
1 Austria 2510071 28.2 Highest
2 Bolivia 888175 7.8 Lowest

>Solution :

Hi and welcome to SO.

If your data frame only has two observations (i.e., rows), what you want is fairly straightforward:

# Create some sample data...
df <- data.frame(
  Country = c("Austria", "Boliva"),
  Ratio = c(28.2, 7.8)
)  

# Create a new variable in the data frame...
df$Rank <- ifelse(df$Ratio == max(df$Ratio), "Highest", "Lowest")
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