如何在dplyr中过滤数据框中不在数值列表中的行

333 阅读1分钟

你可以在dplyr中使用以下基本语法来过滤数据框中不在数值列表中的行:

df %>%
  filter(!col_name %in% c('value1', 'value2', 'value3', ...))

下面的例子展示了如何在实践中使用这种语法。

例1:过滤不包含一个列的值的行

假设我们在R中拥有以下数据框:

#create data frame
df <- data.frame(team=c('A', 'A', 'B', 'B', 'C', 'C', 'D', 'D'),
                 position=c('G', 'G', 'F', 'G', 'F', 'C', 'C', 'C'),
                 points=c(12, 14, 19, 24, 36, 41, 18, 29))

#view data frame
df

  team position points
1    A        G     12
2    A        G     14
3    B        F     19
4    B        G     24
5    C        F     36
6    C        C     41
7    D        C     18
8    D        C     29

下面的语法显示了如何过滤那些球队名称不等于 "A "或 "B "的行:

#filter for rows where team name is not 'A' or 'B'
df %>%
  filter(!team %in% c('A', 'B'))

  team position points
1    C        F     36
2    C        C     41
3    D        C     18
4    D        C     29

例2:过滤不包含多列值的行

假设我们在R中拥有以下数据框:

#create data frame
df <- data.frame(team=c('A', 'A', 'B', 'B', 'C', 'C', 'D', 'D'),
                 position=c('G', 'G', 'F', 'G', 'F', 'C', 'C', 'C'),
                 points=c(12, 14, 19, 24, 36, 41, 18, 29))

#view data frame
df

  team position points
1    A        G     12
2    A        G     14
3    B        F     19
4    B        G     24
5    C        F     36
6    C        C     41
7    D        C     18
8    D        C     29

下面的语法显示了如何过滤那些队名不等于 "A "位置不等于 "C "的行:

#filter for rows where team name is not 'A' and position is not 'C'
df %>%
  filter(!team %in% c('A') & !position %in% c('C'))

  team position points
1    B        F     19
2    B        G     24
3    C        F     36

其他资源

下面的教程解释了如何在dplyr中执行其他常用功能:

如何使用dplyr删除行
如何使用dplyr按索引选择列
如何使用dplyr过滤包含某个字符串的行