【问题标题】:mutate with case_when and contains与 case_when 发生变异并包含
【发布时间】:2017-09-27 12:26:06
【问题描述】:

我觉得应该有一种有效的方法来使用case_whencontains 对带有dplyr 的新列进行变异,但无法使其正常工作。

我知道在 mutate 中使用 case_when 是“有点实验性的”(如在 this 帖子中),但如果您有任何建议,将不胜感激。

不起作用:

library(tidyverse)

set.seed(1234)

x <- c("Black", "Blue", "Green", "Red")

df <- data.frame(a = 1:20, 
                 b = sample(x,20, replace=TRUE))

df <- df %>%
  mutate(group = case_when(.$b(contains("Bl")) ~ "Group1",
                 case_when(.$b(contains("re", ignore.case=TRUE)) ~ "Group2")
  )  

【问题讨论】:

  • 我相信contains 只能在select 内部使用。至少,这是我从?contains 的文档中收集到的。
  • 谢谢 - 是的,我认为这可能是真的,但从文档中不确定。似乎在mutate 中也可能有用,尽管下面的grep 解决方案是一个不错的选择。

标签: r dplyr tidyverse


【解决方案1】:

想添加一些使用str_detectpaste0 函数的示例,这也将使连接公共组变得轻而易举。假设您正在与 gapminder 或其他国家/地区的 df 合作。

interest <- c("Austria", "Belgium", "Bulgaria", "Croatia", "Cyprus",
              "Czech Republic", "Denmark", "Estonia", "Finland",
              "France", "Germany", "Greece", "Hungary", "Ireland",
              "Italy", "Latvia", "Lithuania", "Luxembourg","Malta",
              "The Netherlands", "Poland","Portugal", "Romania",
              "Slovakia", "Slovenia","Spain", "Sweden","United Kingdom")
EU <- paste0(countrycode::countryname(
  sourcevar = interest, destination = "iso2c"), 
  sep = "|", collapse = "")

df%<>%mutate(Region=case_when(
  str_detect(Country, "AT|BE|BG|HR|CY|CZ|DK|EE|FI|FR|DE|GR|HU|IE|
           IT|LV|LT|LU|MT|NL|PL|PT|RO|SK|SI|ES|SE|GB|UK|G8")~ "EU",
  TRUE ~ "Not EU")) ```

You'll need to load `library(magittr)` to get `%<>%` the compound pipe to work, it's basically an abbreviation of `df<-funs(df)`

【讨论】:

    【解决方案2】:

    我们可以使用grep

    df %>%  
       mutate(group = case_when(grepl("Bl", b) ~ "Group1",
                                grepl("re", b, ignore.case = TRUE) ~"Group2"))
    #    a     b  group
    #1   1 Black Group1
    #2   2 Green Group2
    #3   3 Green Group2
    #4   4 Green Group2
    #5   5   Red Group2
    #6   6 Green Group2
    #7   7 Black Group1
    #8   8 Black Group1
    #9   9 Green Group2
    #10 10 Green Group2
    #11  1 Green Group2
    #12  2 Green Group2
    #13  3  Blue Group1
    #14  4   Red Group2
    #15  5  Blue Group1
    #16  6   Red Group2
    #17  7  Blue Group1
    #18  8  Blue Group1
    #19  9 Black Group1
    #20 10 Black Group1
    

    【讨论】:

    • 看起来这也可以用str_detect实现现在:community.rstudio.com/t/…
    • @QAsena 是的,你是对的。 str_detect 也可以,但grep 更通用一点,因为它可以在不同的正则表达式模式下工作,即 perl
    猜你喜欢
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 2020-06-07
    • 2020-07-08
    相关资源
    最近更新 更多