【问题标题】:short hand for using str_detect and & in filter在过滤器中使用 str_detect 和 & 的简写
【发布时间】:2020-04-22 17:05:24
【问题描述】:

我正在尝试将str_detect& 用于filter 数据帧的简写:

library(tidyverse)
df <- data.frame(type = c("age", "age and sex", "sex"))
#          type
# 1         age
# 2 age and sex
# 3         sex

我想缩短这个管道

df %>% 
  filter(str_detect(type, "age") & str_detect(type, "sex"))
#          type
# 1 age and sex 

所以我想通过pattern &lt;- c("age", "sex") 将过滤器通过管道传输到map,并且可能以某种方式使用reduce

谢谢

【问题讨论】:

    标签: r stringr


    【解决方案1】:

    我们可以使用正则表达式来指定零个或多个字符 (*) 在 'age' 后面紧跟 'sex'。 \\b 用于指定单词边界,使其不匹配“格言”等。

    library(dplyr)
    library(stringr)
    df %>% 
       filter(str_detect(type, '\\bage\\b.*\\bsex'))
    

    或使用map/reduce

    library(purrr)
    df %>%
       filter(map(c('age', 'sex'), ~ str_detect(type, .x)) %>% reduce(`&`))
    

    【讨论】:

    • 谢谢,我喜欢!你知道传递向量pattern &lt;- c("age", "sex") 以使用&amp; 过滤的简写吗?
    • @user63230 你可以使用str_c(pattern, collapse = " and ") 然后做一个==
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 2015-02-07
    • 1970-01-01
    相关资源
    最近更新 更多