【问题标题】:R - Filter dataframe to only included rows where the column count meets a criteriaR - 过滤数据框以仅包含列数符合条件的行
【发布时间】:2020-11-21 18:43:19
【问题描述】:

假设这个数据框:

country <- c('USA', 'USA', 'USA', 'USA', 'USA', 'UK', 'UK', 'UK', 'Canada')
number <- c(1:9)
df <- data.frame(country, number)

我希望能够仅对国家计数大于 4 或小于 2 的行进行子集化。所以在这种情况下,它将返回:

country  number
USA      1
USA      2
USA      3
USA      4
USA      5
Canada   9

我可以让它工作:

totalcounts <- filter(count(df, country), n>4 | n<2) # giving me a df of the country and count
for (i in nrow(totalcounts)){
  # code in here that rbinds rows as it matches
}

但我觉得必须有一个更简单的方法。我还没有掌握 sapply 之类的东西,所以我觉得我在这里遗漏了一些东西。看起来我正在走很长的路,并且已经有一些东西可以做到这一点。

【问题讨论】:

    标签: r dataframe filter


    【解决方案1】:

    这是使用subset + ave 的基本 R 选项

    subset(df,!ave(number,country,FUN = function(x) length(x)%in% c(2:4)))
    

    或更短的版本(感谢@Onyambu)

    subset(df,!ave(number,country,FUN = length) %in% 2:4)
    

    这样

      country number
    1     USA      1
    2     USA      2
    3     USA      3
    4     USA      4
    5     USA      5
    9  Canada      9
    

    【讨论】:

    • 你知道你可以缩短这个subset(df,!ave(number,country,FUN = length) %in% 2:4)
    【解决方案2】:

    我们可以通过过滤器进行分组

    library(dplyr)
    df %>% 
       group_by(country) %>% 
       filter(n() > 4|n() < 2)
    # A tibble: 6 x 2
    # Groups:   country [2]
    #  country number
    #  <chr>    <int>
    #1 USA          1
    #2 USA          2
    #3 USA          3
    #4 USA          4
    #5 USA          5
    #6 Canada       9
    

    或者另一种选择是使用add_countfilter 创建一列计数

    df %>%
        add_count(country) %>% 
        filter(n > 4|n < 2) %>% 
        select(-n)
    

    如果我们使用count,也可以加入

    df %>%
        count(country) %>% 
        filter(n >4 |n <2) %>% 
        select(country) %>% 
        inner_join(df)
    

    【讨论】:

      【解决方案3】:

      使用table 的基本 R 选项:

      tab <- table(df$country)
      subset(df, country %in% names(tab[tab > 4 | tab < 2]))
      
      #  country number
      #1     USA      1
      #2     USA      2
      #3     USA      3
      #4     USA      4
      #5     USA      5
      #9  Canada      9
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-23
        • 1970-01-01
        • 1970-01-01
        • 2016-12-05
        • 2020-11-27
        • 1970-01-01
        • 2021-06-20
        相关资源
        最近更新 更多