top_n()对 数据类类型有效吗?

问题描述 投票:0回答:1
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
r dplyr
1个回答
0
投票

感谢@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)
© www.soinside.com 2019 - 2024. All rights reserved.