【问题标题】:Remove rows with NA values and delete those observations in another year [duplicate]删除具有 NA 值的行并在另一年删除这些观察结果[重复]
【发布时间】:2017-12-14 20:35:36
【问题描述】:

我发现为我正在尝试做的事情找到合适的词有点困难。

假设我有这个数据框:

library(dplyr)

# A tibble: 74 x 3
       country  year conf_perc
         <chr> <dbl>     <dbl>
 1      Canada  2017        77
 2      France  2017        45
 3     Germany  2017        60
 4      Greece  2017        33
 5     Hungary  2017        67
 6       Italy  2017        38
 7      Canada  2009        88
 8      France  2009        91
 9     Germany  2009        93
10      Greece  2009        NA
11     Hungary  2009        NA
12       Italy  2009        NA

现在我想删除 2009 年具有 NA 值的行,但我也想删除 2017 年这些国家/地区的行。我想得到以下结果:

# A tibble: 74 x 3
       country  year conf_perc
         <chr> <dbl>     <dbl>
 1      Canada  2017        77
 2      France  2017        45
 3     Germany  2017        60
 4      Canada  2009        88
 5      France  2009        91
 6     Germany  2009        93

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    按“国家”分组后我们可以any

    library(dplyr)
    df1 %>% 
      group_by(country) %>% 
      filter(!any(is.na(conf_perc)))
    # A tibble: 6 x 3
    # Groups:   country [3]
    #  country  year conf_perc
    #    <chr> <int>     <int>
    #1  Canada  2017        77
    #2  France  2017        45
    #3 Germany  2017        60
    #4  Canada  2009        88
    #5  France  2009        91
    #6 Germany  2009        93
    

    【讨论】:

      【解决方案2】:

      baseR解:

      foo <- df$year == 2009 & is.na(df$conf_perc) 
      bar <- df$year == 2017 & df$country %in% unique(df$country[foo])
      df[-c(which(foo), which(bar)), ]
      
      #   country year conf_perc
      # 1  Canada 2017        77
      # 2  France 2017        45
      # 3 Germany 2017        60
      # 7  Canada 2009        88
      # 8  France 2009        91
      # 9 Germany 2009        93
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-13
        • 2014-11-13
        • 2019-11-14
        相关资源
        最近更新 更多