【问题标题】:Remove rows that do NOT contain a letter in them using R使用 R 删除其中不包含字母的行
【发布时间】:2021-06-09 01:07:15
【问题描述】:

我正在尝试过滤掉我的数据,因此我只包含 ID 至少包含一个字母的行(在任何地方)。我很难过,因为我有这么多行带有随机字符或随机空格,所以即使我尝试过滤掉空格,它也会错过它们。

这是我的数据:

library(tidyverse)
test <- tibble(id = c("   ", "91a", "90", "ab"),
               score = c(5, 10, 15, 91))

这就是我想要的:

library(tidyverse)
answer <- tibble(id = c("91a","ab"),
               score = c(10, 91))

谢谢!

【问题讨论】:

    标签: r regex text filter data-cleaning


    【解决方案1】:

    您可以使用stringr 包中的str_detect 来检测id 变量中是否存在模式。

    library(dplyr)
    library(stringr)
    library(tibble)
    
    test <- tibble(id = c("   ", "91a", "90", "ab"),
                   score = c(5, 10, 15, 91))
    
    filter(test, str_detect(id, '[a-zA-Z]'))
    
    #> # A tibble: 2 x 2
    #>   id    score
    #>   <chr> <dbl>
    #> 1 91a      10
    #> 2 ab       91
    

    reprex package (v0.3.0) 于 2021-03-10 创建

    【讨论】:

      【解决方案2】:

      你可以使用:

      subset(test, grepl('[a-zA-Z]', id))
      
      #   id    score
      #  <chr> <dbl>
      #1 91a      10
      #2 ab       91
      

      或者在dplyr

      library(dplyr)
      test %>% filter(grepl('[a-zA-Z]', id))
      

      【讨论】:

        猜你喜欢
        • 2015-04-08
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 2016-12-16
        • 1970-01-01
        • 2019-06-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多