【问题标题】:Delete NAs, based on duplicated ID variables根据重复的 ID 变量删除 NA
【发布时间】:2020-11-17 16:28:43
【问题描述】:

我的数据看起来像这样

zz <- 'wb_iso3c                   country year wbclass
1:      YUG "Serbia and Montenegro (former)" 1990    NA
2:      YUG            "Yugoslavia (former)" 1990      UM
3:      YUG "Yugoslavia (former)" 1991    NA
4:      YUG            "Serbia and Montenegro (former)" 1991      UM
5:      YUG "Serbia and Montenegro (former)" 1992      NA
6:      YUG            "Yugoslavia (former)" 1992    NA'
Data <- read.table(text=zz, header = TRUE)

在以下情况下,我想找到一种系统有效地放弃观察的方法: 仅考虑wb_iso3cyear,我的观察结果是重复的。 (因此我不在乎另一个变量,例如 country 是否具有不同的值)。在“重复”的观察中,我想保留 wbclass 不是 NA 的观察结果。如果 wbclassNA 对于两个观察结果,保留哪一行无关紧要。

最终的数据集应该是这样的

   wb_iso3c                        country year wbclass
1:      YUG            Yugoslavia (former) 1990      UM
2:      YUG Serbia and Montenegro (former) 1991      UM
3:      YUG Serbia and Montenegro (former) 1992    <NA>

非常感谢您的帮助。如果你可以使用 dyplr 的 data.table 那就太好了。

【问题讨论】:

    标签: r data-manipulation missing-data


    【解决方案1】:

    使用dplyr,您可以尝试以下操作。

    首先是group_bywb_iso3cyear,目的是为这两列的每个不同组合获得一个观察结果。

    然后arrange(排序顺序)组内的wbclass 列。使用arrangeNA 值将始终排在末尾。

    那么slice(1)会保留每组的第一行数据。

    library(dplyr)
    
    Data %>%
      group_by(wb_iso3c, year) %>%
      arrange(wbclass) %>%
      slice(1)
    

    输出

      wb_iso3c country                         year wbclass
      <chr>    <chr>                          <int> <chr>  
    1 YUG      Yugoslavia (former)             1990 UM     
    2 YUG      Serbia and Montenegro (former)  1991 UM     
    3 YUG      Serbia and Montenegro (former)  1992 NA 
    

    【讨论】:

      【解决方案2】:

      一个很长的base R 解决方案可以基于重复值的测试,然后计算一个变量来存储欺骗和NA。之后,您可以过滤并获得预期的结果。代码如下:

      #Code
      Data$i1 <- duplicated(paste(Data$wb_iso3c,Data$year),fromLast = T)
      Data$i2 <- ifelse(Data$i1 & is.na(Data$wbclass),1,0)
      Data2 <- Data[Data$i2==0,]
      Data2$i1 <- NULL
      Data2$i2 <- NULL
      

      输出:

         wb_iso3c                        country year wbclass
      2:      YUG            Yugoslavia (former) 1990      UM
      4:      YUG Serbia and Montenegro (former) 1991      UM
      6:      YUG            Yugoslavia (former) 1992    <NA>
      

      【讨论】:

        猜你喜欢
        • 2016-09-16
        • 2019-08-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        • 2019-06-22
        • 1970-01-01
        • 2017-07-15
        相关资源
        最近更新 更多