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
多亏了@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)