mutate with case_when and contains

前端 未结 1 1416
终归单人心
终归单人心 2020-12-05 19:51

I feel like there should be an efficient way to mutate new columns with dplyr using case_when and contains, but cannot get it to work.

相关标签:
1条回答
  • 2020-12-05 20:25

    We can use 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
    
    0 讨论(0)
提交回复
热议问题