【问题标题】:Find max value in a column that contain -Inf and NA values while using dplyr and tidyR functions在使用 dplyr 和 tidyR 函数时在包含 -Inf 和 NA 值的列中查找最大值
【发布时间】:2021-05-04 12:35:41
【问题描述】:

我有一个看起来像这样的数据框,我想使用 col1 找到最大值 slice_n、top_n等dplyr函数

df = data.frame(col1=c(-Inf, 10,NaN, NA,200,Inf), col2=c(30,30, 10,200,20,10))
 col1 col2
  -Inf   30
    10   30
   NaN   10
    NA  200
   200   20
   Inf   10

到目前为止,我还没有解决这个问题,我想知道社区是否可以帮助我或给我提示。非常感谢您的宝贵时间

【问题讨论】:

  • 您对该示例的预期输出是什么?
  • 200 col1 的最大值 :)
  • df %>% filter(!is.na(col1) & !col1 %in% c(Inf, -Inf)) %>% slice_max(col1)

标签: r dplyr tidyverse


【解决方案1】:

要找到col1 中的最大非无限值:

df %>% 
  filter(!is.infinite(col1)) %>% 
  summarise(Max=max(col1, na.rm=TRUE)) %>%
  pull(Max)

[1] 200

或者

max(df$col1[!is.infinite(df$col1)], na.rm=TRUE)
[1] 200

col1中查找包含最大非无限值的行:

df %>% filter(!is.infinite(col1)) %>% slice_max(col1) 
  col1 col2
1  200   20

filter() 的调用是为了响应 OP 的指示,即它们需要返回非无限值。如果可以接受无限值,只需省略调用即可。请注意,slice_max 等人,按照 OP 在他们的问题中的要求,不返回 列中的值,而是返回 数据框中的行

请注意,top_n() 已被取代。

【讨论】:

    【解决方案2】:
    df %>% gather() %>% group_by(key) %>% slice_max(value)
    

    【讨论】:

    • gather 已停用。现在推荐pivot_longer
    • 这个函数会给你输出 200 吗?
    • 是的,Inf 和 200
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 2015-06-29
    相关资源
    最近更新 更多