【问题标题】:Does `top_n()` work for <Date> data class types?`top_n()` 是否适用于 <Date> 数据类类型?
【发布时间】:2019-10-25 21:32:44
【问题描述】:
set.seed(1)
library(tidyverse)
df <- tibble(col1 = c(rep("a", 4), c(rep("b", 4))),
             col2 = as.Date(c("2019-01-01", "2019-02-01", "2019-03-01", 
                              "2019-04-01", "2019-01-01", "2019-02-01", 
                              "2019-03-01", "2019-04-01")),
             col3 = runif(8))
#> # A tibble: 8 x 3
#>   col1  col2        col3
#>   <chr> <date>     <dbl>
#> 1 a     2019-01-01 0.266
#> 2 a     2019-02-01 0.372
#> 3 a     2019-03-01 0.573
#> 4 a     2019-04-01 0.908
#> 5 b     2019-01-01 0.202
#> 6 b     2019-02-01 0.898
#> 7 b     2019-03-01 0.945
#> 8 b     2019-04-01 0.661

我想从上面数据框中的每个组中过滤掉最新的月份(过滤掉 2019-04-01)。我认为下面的dplyr 代码可以解决问题。但是dplyr::top_n() 似乎没有在我的col2 上工作。是因为col2 是“日期”类吗?奇怪的警告是怎么回事?最后,一旦我得到某种类型的工作代码,我可以使用dplyr::top_n(-1, col2) 而不是dplyr::top_n(3, col2) 来摆脱最大值吗?

df %>% group_by(col1) %>% top_n(col2, 3)
#> # A tibble: 8 x 3
#> # Groups:   col1 [2]
#>   col1  col2         col3
#>   <chr> <date>      <dbl>
#> 1 a     2019-01-01 0.629 
#> 2 a     2019-02-01 0.0618
#> 3 a     2019-03-01 0.206 
#> 4 a     2019-04-01 0.177 
#> 5 b     2019-01-01 0.687 
#> 6 b     2019-02-01 0.384 
#> 7 b     2019-03-01 0.770 
#> 8 b     2019-04-01 0.498 
#> Warning messages:
#> 1: In if (n > 0) { :
#>   the condition has length > 1 and only the first element will be used
#> 2: In if (n > 0) { :
#>   the condition has length > 1 and only the first element will be used

【问题讨论】:

  • 您使用的参数顺序错误。使用top_n(3, col2) 更正顺序或将参数命名为top_n(wt = col2, n = 3)。否定的n 将从底部选择,有关详细信息,请参阅?top_n
  • ...所以你可以做top_n(-(n() - 1), wt)。但我可能会改用... %&gt;% arrange(col2) %&gt;% slice(-1)。对于slice,负索引被移除。看起来更清晰了。
  • @Gregor 谢谢,为什么top_n(iris, 5, Sepal.Width) 返回六个结果,而它只是“前 5”?奇怪。
  • 再次,我会将您指向帮助页面?top_n“请注意,我们在这里获得了超过 2 个值,因为存在平局:top_n() 要么接受所有具有值的行,要么不接受。”
  • @Gregor 抱歉,当我查看时我没有注意到3.9 的两个值。认为它们是六个独特的价值。谢谢。

标签: r dplyr


【解决方案1】:

感谢@Gregor,我只是把订单颠倒了。

df %>% group_by(col1) %>% top_n(col2, 3)  # wrong order

应该是:

df %>% group_by(col1) %>% top_n(3, col2)  # right order

或者我可以彻底地为这些论点命名:

df %>% group_by(col1) %>% top_n(wt = col2, n = 3)

【讨论】:

    猜你喜欢
    • 2014-08-27
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 2012-02-29
    • 2017-07-18
    相关资源
    最近更新 更多