首页 > 解决方案 > 从R中的数据框中删除字符串

问题描述

我想从数据框中的第二列中删除带有字符串(完全匹配)的行:

输入:

   >data

      habitat       species
         wet species1_ind1
         wet species1_ind1
         dry species2_ind1
         dry species2_ind1
         dry species3_ind1
         dry species3_ind1
         ...

所需的输出(删除了包含 species2_ind1 的行):

    >new_data

      habitat       species
         wet species1_ind1
         wet species1_ind1
         dry species3_ind1
         dry species3_ind1
         ...

理想情况下,我想提供要从数据框中删除的字符串列表。

标签: rdataframe

解决方案


你可以这样做%in%

data[!(data$species %in% c("species2_ind1")), ]
  habitat       species
1     wet species1_ind1
2     wet species1_ind1
5     dry species3_ind1
6     dry species3_ind1

详细信息: 这是选择species不在列表中的行。数据既有行又有列。当您指定时data[x,y]x 给出行而 y 给出列。data[x, ]表示您已经用 x 指定了行,但取了所有列。上面的表达式采用所有列,但将行指定为!(data$species %in% c("species2_ind1")).
data$species %in% c("species2_ind1"))给出 data$species 的值在列表中的那些行. 但那些是我们想要排除的,所以我们使用!否定逻辑表达式并获取不在列表中 data$species的行。


推荐阅读