【问题标题】:How to use regular expressions with dplyr's select helper functions如何将正则表达式与 dplyr 的选择辅助函数一起使用
【发布时间】:2019-12-27 12:29:40
【问题描述】:

使用 dplyr 使用各种帮助函数(例如 contains())选择列非常简单。在这些函数的帮助文件中,参数被称为“文字字符串”。但是,可以改用正则表达式吗?

以下示例有效:

library(dplyr)
iris %>%
   select(contains("Species"))

以下正则表达式示例没有:

# Select all column names that end with lower case "s"
iris %>%
   select(contains("s$"))

# Not run
data frame with 0 columns and 150 rows

我想知道是否可以在 dplyr select 辅助函数中使用正则表达式,如果可以,它们的实现。

如果这不可能,我将使用替代方法(例如,base 或 data.table)来回答。作为背景,我的最终目标是使用summarise_at() 函数或等效函数来对所有以数字结尾的列求和(即正则表达式[0-9]$)。

【问题讨论】:

标签: r regex dplyr


【解决方案1】:

我们也可以使用base R中的endsWith

subset(iris, select = endsWith(names(iris), "s")) 

【讨论】:

    【解决方案2】:

    选择帮助函数matches()可用于匹配正则表达式:

    library(dplyr)
    
    out <- select(iris, matches("s$"))
    
    head(out)
    #>   Species
    #> 1  setosa
    #> 2  setosa
    #> 3  setosa
    #> 4  setosa
    #> 5  setosa
    #> 6  setosa
    

    【讨论】:

      【解决方案3】:

      使用dplyr,可以使用ends_with

      iris %>% 
        select(ends_with("s")) %>% 
         head(3)
        Species
      1  setosa
      2  setosa
      3  setosa
      

      使用basegrepl

      head(iris[grepl("s$",names(iris),ignore.case = FALSE)])
        Species
      1  setosa
      2  setosa
      3  setosa
      4  setosa
      5  setosa
      6  setosa
      

      或者使用purrr:

      iris %>% 
         purrr::keep(grepl("s$",names(.))) %>% 
         head()
        Species
      1  setosa
      2  setosa
      3  setosa
      4  setosa
      5  setosa
      6  setosa
      

      【讨论】:

        猜你喜欢
        • 2016-09-07
        • 2019-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-02
        • 2015-12-18
        • 2016-12-29
        相关资源
        最近更新 更多