【问题标题】:Setting condition for max within mutate function of dplyr在 dplyr 的 mutate 函数中设置最大值的条件
【发布时间】:2019-01-30 07:06:10
【问题描述】:

我希望确定数据集中的最高分数,但仅在查看群体人数高于某个阈值时,在本例中为 20 以上。样本数据:

Race = c("African American", "Asian", "Hispanic", "White")
Population = c(28, 11, 31, 64)
Average_Score = c(65, 82, 49, 75)
df = data.frame(Race, Population, Average_Score)

    Race            Population Average_Score
1 African American      28           65
2 Asian                 11           82
3 Hispanic              31           49
4 White                 64           75

我想做的是这样的:

df %>% mutate(reference=max(Average_Score)) where Population > 20

但是,我需要添加一个条件,以便它仅在 Population 大于 20 时提取 max(Average_Score)。在这种情况下,而不是返回 Average_Score 的 82(因为亚洲人口小于 20)它会返回 75 的 Average_Score(因为 Population 大于 20 的任何组的最高 Average_Score 是与 White 重合的 Average_Score)

任何帮助将不胜感激。

【问题讨论】:

  • 你需要max(Average_Score[Population > 20])
  • 谢谢!效果很好!

标签: r conditional max dplyr


【解决方案1】:

我使用了akrun的建议:

max(Average_Score[Population > 20])

但 nycrefugee 也有效:

df %>% 
  filter(Population > 20) %>%
  filter(Average_Score == max(Average_Score))

【讨论】:

    【解决方案2】:

    dplyr 解决方案可能会提供更多灵活性。

    df %>% 
      filter(Population > 20) %>%
      filter(Average_Score == max(Average_Score))
    
       Race Population Average_Score
    1 White         64            75
    

    【讨论】:

    • 谢谢!设置代码的方式,我最终使用了上面 akrun 建议的代码:max(Average_Score[Population > 20])
    猜你喜欢
    • 2018-11-11
    • 2023-04-10
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    相关资源
    最近更新 更多