【问题标题】:Filter out all rows with only one period in R过滤掉R中只有一个句点的所有行
【发布时间】:2018-11-20 17:43:47
【问题描述】:

我有这个专栏,Identifier,其中包含字符值。

structure(list(Identifier = c("RL.K", "RL.K.1", "RL.K.2", "RL.K.3", 
"RL.K.4", "RL.K.5", "RL.K.6", "RL.K.7", "RL.K.9", "RL.K.10", 
"RI.K", "RI.K.1", "RI.K.2", "RI.K.3", "RI.K.4", "RI.K.5", "RI.K.6", 
"RI.K.7", "RI.K.9", "RI.K.10", "RF.K", "RF.K.1")), row.names = c(NA, 
-22L), class = c("tbl_df", "tbl", "data.frame"))

如何过滤掉只有一个句点的值?这样我就可以取出第 1、11 和 21 行

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    如果我们要使用 base 和 grepl,有一个更简单的正则表达式代码:

    df[grepl("\\..*\\.", df$Identifier),]
    

    (正则表达式的解释:\\. 查找文字 .,.* 查找任何内容,因此此代码查找有两个文字点被任何内容分隔的情况)

    【讨论】:

      【解决方案2】:

      使用基数 R 的解决方案。(找到所有恰好只有一个点的字符串)

      grepl("^[^.]*[.][^.]*$", df1$Identifier)
      

      要删除带有一个点的行,请使用:

      df1[
      !grepl("^[^.]*[.][^.]*$", df1$Identifier),
      ]
      

      【讨论】:

      • 它需要一个!grepl 表达式之前,因为您想过滤掉那些只有一个. 正则表达式正在搜索的人。
      • 感谢@Gwang-JinKim。我刚刚意识到“过滤掉”的意思是“删除”。
      【解决方案3】:

      我们可以计算“标识符”中.的数量,并为filter行创建逻辑条件

      library(tidyverse)
      df1 %>% 
         filter(str_count(Identifier, "[.]") == 1)
      # A tibble: 3 x 1
      #  Identifier
      #  <chr>     
      #1 RL.K      
      #2 RI.K      
      #3 RF.K      
      

      或者正如@WiktorStribizew 提到的,fixed 可以被包装以使其更快

      df1 %>% 
         filter(str_count(Identifier, fixed(".")) == 1)
      

      或者不使用任何外部库,

      df1[nchar(gsub("[^.]*", "", df1$Identifier)) == 1,]
      

      或者使用来自base Rgregexpr

      df1[lengths(gregexpr(".", df1$Identifier, fixed = TRUE)) == 1,]
      

      【讨论】:

      • 为什么是正则表达式?只需找到一个点,使用str_count(Identifier, fixed("."))
      • 哇,这太快了!
      【解决方案4】:

      使用尽可能少的正则表达式;):

      has.only.one.dot <- function(str_vec) sapply(strsplit(str_vec, "\\."), function(vec) length(vec) == 2)
      df[!has.only.one.dot(df$Identifier), ]
      

      但是,sapplystrsplit 列表函数比正则表达式解决方案要慢。

      has.only.one.dot <- function(str_vec) grepl("\\.", str_vec) & ! grepl("\\..*\\.", str_vec)
      df[!has.only.one.dot(df$Identifier), ]
      

      【讨论】:

        猜你喜欢
        • 2022-11-02
        • 2021-11-14
        • 2013-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多