【问题标题】:Removing character strings from dataframe in R从R中的数据框中删除字符串
【发布时间】:2018-08-25 18:46:58
【问题描述】:

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

输入:

   >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
         ...

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

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    您可以通过%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 不为 的行。

    【讨论】:

    • c("species2_ind1")) 后面的感叹号和逗号的作用是什么?
    • 将添加到答案中。
    • 当您删除 3:4 的行时,输出是否可以从 1:4 而不是 1:2 和 5:6 跳过已删除的行?
    • 行号如上,但如果你希望它们只是一个向上的编号,删除3&4后你可以使用row.names(data) = 1:nrow(data)
    猜你喜欢
    • 2021-10-05
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 2019-10-30
    • 2021-11-08
    相关资源
    最近更新 更多