【问题标题】:How to remove a specific number of matching entries from a dataframe?如何从数据框中删除特定数量的匹配条目?
【发布时间】:2018-04-20 08:32:47
【问题描述】:

我有两个数据框:

subset <- data.frame(id=rep(1,7), country=c("CH", "CH", "CA", "DE", "FR", "AT", "DE"))

> subset
  id country
1  1      CH
2  1      CH
3  1      CA
4  1      DE
5  1      FR
6  1      AT
7  1      DE

whotoremove <- data.frame(id = c(1,1), country = c("DE", "FR"))

> whotoremove
  id country
1  1      DE
2  1      FR

我想从subset 中删除来自whotoremove 的元素,不仅通过匹配,而且还通过它们出现的次数。也就是说,我想得到类似的东西:

> subset
  id country
1  1      CH
2  1      CH
3  1      CA
6  1      AT
7  1      DE

请注意行名:我想保留原始子集中的行名,因为我需要它们。

【问题讨论】:

    标签: r data-manipulation


    【解决方案1】:
    idx <- match(whotoremove$country, subset$country)
    subset[-idx, ]
    

    输出为:

      id country
    1  1      CH
    2  1      CH
    3  1      CA
    6  1      AT
    7  1      DE
    

    样本数据:

    subset <- data.frame(id=rep(1,7), country=c("CH", "CH", "CA", "DE", "FR", "AT", "DE"))
    whotoremove <- data.frame(id = c(1,1), country = c("DE", "FR"))
    

    【讨论】:

      【解决方案2】:

      dplyr 的一个解决方案是:

      library(dplyr)
      
      whotoremove <- whotoremove %>% 
        group_by(id, country) %>% 
        mutate(count = 1:n()
      
      subset %>%
        rownames_to_column() %>% 
        group_by(id, country) %>% 
        mutate(count = 1:n()) %>% 
        anti_join(whotoremove, by = c("id", "country", "count")) 
      
      # A tibble: 5 x 4
      # Groups:   id, country [?]
      #   rowname    id country count
      #   <chr>   <dbl> <fct>   <int>
      # 1 1          1. CH          1
      # 2 2          1. CH          2
      # 3 3          1. CA          1
      # 4 6          1. AT          1
      # 5 7          1. DE          2
      

      为了保留行名,我使用rownames_to_column-函数并删除匹配的行,我使用anti_join。为了只删除组合发生的次数,我首先引入了一个count-变量并将它们作为一个列合并到anti_join。

      【讨论】:

        猜你喜欢
        • 2012-10-26
        • 2012-12-04
        • 1970-01-01
        • 2018-04-13
        • 2011-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-17
        相关资源
        最近更新 更多