【问题标题】:case_when with partial string match and contains()case_when 与部分字符串匹配和 contains()
【发布时间】:2019-10-28 11:55:59
【问题描述】:

我正在处理一个数据集,该数据集包含许多名为 status1、status2 等的列。在这些列中,它表示某人是否是豁免、完整、注册等。

很遗憾,豁免输入不一致;这是一个示例:

library(dplyr)

problem <- tibble(person = c("Corey", "Sibley", "Justin", "Ruth"),
                  status1 = c("7EXEMPT", "Completed", "Completed", "Pending"),
                  status2 = c("exempt", "Completed", "Completed", "Pending"),
                  status3 = c("EXEMPTED", "Completed", "Completed", "ExempT - 14"))

我正在尝试使用 case_when() 创建一个具有最终状态的新列。如果它曾经说已完成,那么它们就完成了。如果它曾经说豁免但没有说完整,那么他们是豁免的。

重要的部分是我希望我的代码使用 contains("status"),或仅针对状态列且不需要全部输入的等效项,并且我希望它只需要部分字符串匹配豁免。

至于在 case_when 中使用 contains,我看到了这个示例,但无法将其应用于我的案例:mutate with case_when and contains

这是我迄今为止尝试使用的,但正如你所猜想的那样,它没有奏效:

library(purrr)
library(dplyr)
library(stringr)
solution <- problem %>%
  mutate(final= case_when(pmap_chr(select(., contains("status")), ~
    any(c(...) == str_detect(., "Exempt") ~ "Exclude",
               TRUE ~ "Complete"
  ))))

这是我希望最终产品的样子:

solution <- tibble(person = c("Corey", "Sibley", "Justin", "Ruth"),
                   status1 = c("7EXEMPT", "Completed", "Completed", "Pending"),
                   status2 = c("exempt", "Completed", "Completed", "Pending"),
                   status3 = c("EXEMPTED", "Completed", "Completed", "ExempT - 14"),
                   final = c("Exclude", "Completed", "Completed", "Exclude")) 

谢谢!

【问题讨论】:

    标签: r string dplyr contains stringr


    【解决方案1】:

    我认为你是在倒退。将case_when 放在pmap_chr 中,而不是相反:

    library(dplyr)
    library(purrr)
    library(stringr)
    
    problem %>%
      mutate(final = pmap_chr(select(., contains("status")), 
                              ~ case_when(any(str_detect(c(...), "(?i)Exempt")) ~ "Exclude",
                                          TRUE ~ "Completed")))
    

    对于每个pmap 迭代(problem 数据集的每一行),我们想使用case_when 来检查是否存在字符串Exempt。 (?i) in str_detect 使其不区分大小写。这和写str_detect(c(...), regex("Exempt", ignore_case = TRUE))是一样的

    输出:

    # A tibble: 4 x 5
      person status1   status2   status3     final    
      <chr>  <chr>     <chr>     <chr>       <chr>    
    1 Corey  7EXEMPT   exempt    EXEMPTED    Exclude  
    2 Sibley Completed Completed Completed   Completed
    3 Justin Completed Completed Completed   Completed
    4 Ruth   Pending   Pending   ExempT - 14 Exclude
    

    【讨论】:

    • 谢谢!快速提问:你能解释一下 (?i) 是什么意思吗?
    • @J.Sabree 只是在编辑我的答案。它是一个打开不区分大小写模式的正则表达式修饰符。看到这个答案:stackoverflow.com/questions/15145659/…
    • 感谢您的回答和解释!解释确实有助于应用于新代码。
    猜你喜欢
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 2020-09-24
    • 2019-10-18
    • 2017-07-02
    相关资源
    最近更新 更多