简体   繁体   English

使用 if 比较列值

[英]Using if to compare column values

Here's my df, labeled "Task".这是我的 df,标有“任务”。

Country国家 Confirmed确认的 Ratio比率
1 1个 Austria奥地利 2510071 2510071 28.2 28.2
2 2个 Bolivia玻利维亚 888175 888175 7.8 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.我需要使用 if-else 语句来做两件事:(1) 确定“比率”列中的哪个值更大,以及 (2) 创建一个新列,为适当的观察。

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".我已经阅读了很多关于使用 if-else 的帖子,但我似乎找不到这样的条件示例:“查看此行中的‘比率’值是否大于或小于另一行中的‘比率’值” . I've made lots of if() attempts, but they've all failed pretty miserably.我做了很多 if() 尝试,但都失败得很惨。

My goal is code that'll produce this output:我的目标是生成此 output 的代码:

Country国家 Confirmed确认的 Ratio比率 Rank
1 1个 Austria奥地利 2510071 2510071 28.2 28.2 Highest最高
2 2个 Bolivia玻利维亚 888175 888175 7.8 7.8 Lowest最低

If your data frame only has two observations (ie, 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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM