Home > other >  Using if to compare column values
Using if to compare column values

Time:02-24

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.

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

CodePudding user response:

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")
  • Related