grepl in R to find matches to any of a list of character strings

后端 未结 3 1407
离开以前
离开以前 2020-12-05 05:23

Is it possible to use a grepl argument when referring to a list of values, maybe using the %in% operator? I want to take the data below and if the animal name has \

3条回答
  •  离开以前
    2020-12-05 05:53

    Try to avoid ifelse as much as possible. This, for example, works nicely

    c("Discard", "Keep")[grepl("(dog|cat)", data$animal) + 1]
    

    For a 123 seed you will get

    ##  [1] "Keep"    "Keep"    "Discard" "Keep"    "Keep"    "Keep"    "Discard" "Keep"   
    ##  [9] "Discard" "Discard" "Keep"    "Discard" "Keep"    "Discard" "Keep"    "Keep"   
    ## [17] "Keep"    "Keep"    "Keep"    "Keep"    "Keep"    "Keep"    "Keep"    "Keep"   
    ## [25] "Keep"    "Keep"    "Discard" "Discard" "Keep"    "Keep"    "Keep"    "Keep"   
    ## [33] "Keep"    "Keep"    "Keep"    "Discard" "Keep"    "Keep"    "Keep"    "Keep"   
    ## [41] "Keep"    "Discard" "Discard" "Keep"    "Keep"    "Keep"    "Keep"    "Discard"
    ## [49] "Keep"    "Keep"   
    

提交回复
热议问题