首页 > 解决方案 > 基于R中的多个字符串列过滤行

问题描述

给定如下数据框:

  city type  count
0   bj    a     10
1   bj    a     23
2   bj    b     12
3   bj    c     34
4   sh    a     17
5   sh    b     18
6   sh    c     25
7   sh    c     13
8   sh    a     12

我想根据citytype:过滤行bj-a, bj-c, sh-b,预期的结果将是这样的:

  city type  count
0   bj    a     10
1   bj    a     23
2   bj    c     34
3   sh    b     18

我怎么能在 R 中做到这一点?谢谢。

标签: r

解决方案


您可以使用subset

subset(df, city == 'bj' & type %in% c('a', 'c') | city == 'sh' & type == 'b')

#  city type count
#0   bj    a    10
#1   bj    a    23
#3   bj    c    34
#5   sh    b    18

filterdplyr

library(dplyr)
df %>%
  filter(city == 'bj' & type %in% c('a', 'c') | 
         city == 'sh' & type == 'b')

推荐阅读