【问题标题】:Filtering matching rows in a single data.frame过滤单个data.frame中的匹配行
【发布时间】:2015-11-30 22:51:50
【问题描述】:

我在过滤专利数据时不知何故陷入了困境。所以想象一下你有:

expl <- data.frame(PatNr=c(1,1,1,2,2,2,2,2), Country=c("AZ","AZ","PE","AZ","PS","HQ","HQ","PV"))

#>   PatNr    Country
#> 1       1        AZ
#> 2       1        AZ
#> 3       1        PE
#> 4       2        AZ
#> 5       2        PS
#> 6       2        HQ
#> 7       2        HQ
#> 8       2        PV

我想要的是在我的 data.frame 中只包含那些包含 AZ 和 PS 的 PatNr 案例。可以删除所有其他 PatNr 案例。因此,在给定的示例中,我希望脚本删除所有 PatNr=1 行并保留 PatNr=2 行。

在这种情况下将行子化为两行会很棘手,因为实际数据附加了九个关键变量,每行不同。

【问题讨论】:

  • 为了清楚起见,您要选择具有两个国家的专利号:AZ 和 PS。对吗?
  • 哦,是的,请。这就是我遇到的问题,只获得包含两个国家而不是其中一个国家的那些。现在得试试你的解决方案,看起来很有希望!

标签: r filter dataframe


【解决方案1】:

使用基础 R

res <- lapply(split(expl, expl$PatNr), lvls = c("AZ", "PS"), function(y, lvls)     { 
   y[all(lvls %in% y$Country)]
})
do.call(rbind, res)
    PatNr Country
2.4     2      AZ
2.5     2      PS
2.6     2      HQ
2.7     2      HQ
2.8     2      PV

【讨论】:

    【解决方案2】:

    使用 dplyr:

    library(dplyr)
    
    
    expl2 <- expl %>% 
      group_by(PatNr) %>% 
      filter(all(c("AZ","PS") %in% Country)) 
    expl2
    

    【讨论】:

      【解决方案3】:

      这是一个凌乱的 for 循环,可以解决问题:我确信有更好的方法,但这应该可以工作

      todelete=numeric(0)
      for(i in unique(expl$PatNr)){
        countries = as.character(unique(expl$Country[expl$PatNr==i]))
        if(!all(c("AZ", "PS") %in% countries)){
          todelete=c(todelete, i)
        }
      }
      
      
      expl[!expl$PatNr %in% todelete,]
      

      【讨论】:

        猜你喜欢
        • 2019-10-29
        • 1970-01-01
        • 2019-07-13
        • 2020-01-27
        • 1970-01-01
        • 2019-08-28
        • 2018-02-16
        • 1970-01-01
        • 2011-02-26
        相关资源
        最近更新 更多