【问题标题】:grepl for any string allowedgrepl 用于允许的任何字符串
【发布时间】:2019-05-30 14:15:29
【问题描述】:

我正在构建一个由函数参数提供的 grepl 命令。如果不需要,我想跳过 grep 命令。我可以使用控制语句来做到这一点,但我想传递一个返回所有字符串的值。

some_sub <- function(data, descr="*.*"){
     return(data %>% filter(grepl(descr, description)))
} 

我想要以下工作:

some_sub(data, "Cabbage")
some_sub(data) # returns everything

数据在哪里

data <- structure(list(description = structure(c(1L, 1L, 2L, 1L), 
                                   .Label = c("Cabbage","Carrot"), 
                                   class = "factor"), 
           weight = c(12L, 9L, 7L, 15L)), 
      class = "data.frame", 
      row.names = c(NA,-4L))

【问题讨论】:

    标签: r grepl


    【解决方案1】:

    一个选项是只使用.(因为它是任何字符的元字符)作为descr参数的默认匹配

    添加了一个参数 colNm 以更概括一点

    如果有空格 ("") 并且想要匹配它们,最好将 * 作为默认值

    some_sub <- function(data, colNm, descr="."){
     colNm <- enquo(colNm)
     data %>%
          filter(grepl(descr, !!colNm))
    } 
    
    some_sub(iris, Species, "setosa")
    some_sub(iris, Species)
    

    使用 OP' 数据

    some_sub(data, description, "Cabbage")
    #  description weight
    #1     Cabbage     12
    #2     Cabbage      9
    #3     Cabbage     15
    
    some_sub(data, description)
    #  description weight
    #1     Cabbage     12
    #2     Cabbage      9
    #3      Carrot      7
    #4     Cabbage     15
    

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      • 1970-01-01
      相关资源
      最近更新 更多