【问题标题】:Filtering by year equal or smaller than threshold按等于或小于阈值的年份过滤
【发布时间】:2021-02-11 01:05:07
【问题描述】:

我有多年的国家数据,并且想要过滤每个国家/地区的最后一次观察,其中年份等于或小于 X 年。因此,我希望每个国家/地区都有唯一的行:

library(tidyverse)

df <- tibble("country" = c(rep("AFG", 3),  rep("BEN", 3), rep("CHE", 3)),
             "year" = c(2001, 2005, 2009, 2001, 2004, 2009, 2000, 2003, 2008), 
             "value" = rnorm(9, 50))

df %>% 
  filter(year <= 2008)
#> # A tibble: 7 x 3
#>   country  year value
#>   <chr>   <dbl> <dbl>
#> 1 AFG      2001  51.0
#> 2 AFG      2005  49.9
#> 3 BEN      2001  50.2
#> 4 BEN      2004  49.2
#> 5 CHE      2000  50.8
#> 6 CHE      2003  49.0
#> 7 CHE      2008  48.3

reprex package (v0.3.0) 于 2021-02-10 创建

而我想要的结果是:

#>   country year  value
#>   <chr>   <chr> <dbl>
#> 1 AFG     2005   50.8
#> 2 BEN     2004   49.5
#> 3 CHE     2008   49.9

如何实现这一点(最好使用矢量化解决方案而不是 for 循环)?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    只保留 2008 年或以下的行,arrange 的数据由 year 和每个 country 选择最后一行。

    library(dplyr)
    
    df %>%
      filter(year <= 2008) %>%
      arrange(country, year) %>%
      group_by(country) %>%
      slice(n())
    
    #  country  year value
    #  <chr>   <dbl> <dbl>
    #1 AFG      2005  48.5
    #2 BEN      2004  49.1
    #3 CHE      2008  49.3
    

    【讨论】:

      【解决方案2】:

      我们可以使用

       library(dplyr)
       df %>%
              filter(year <= 2008) %>%
              arrange(country, year) %>%
              group_by(country) %>%
              filter(row_number() == n())
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-04
        • 2021-11-23
        • 2017-06-16
        • 2022-08-18
        • 2021-01-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多