Search code examples
rif-statementdplyrlogical-operatorslogical-or

ifelse statement using logical condition in R


I have this data frame

DF
ID    WORD_LIST   
1     APPLE
2     RED
3     SNOW
4     ANKARA
5     RENEW

I would like to select only word starting with "A" or "R"

DF
ID    WORD_LIST    WORDS_A_R  
1     APPLE        APPLE
2     RED          RED
3     SNOW         NA
4     ANKARA       ANKARA
5     RENEW        RENEW

I tried this code

DF %>% mutate(WORDS_A_R = ifelse(grepl("^A" | "^R", WORD_LIST), as.character(WORD_LIST), NA))

But this error occurs

operations are possible only for numeric, logical or complex types

Solution

  • You can use :

    transform(df, WORDS_A_R  = ifelse(grepl("^[AR]", WORD_LIST), WORD_LIST, NA))
    

    If you prefer dplyr :

    library(dplyr)
    df %>%
      mutate(WORDS_A_R  = ifelse(grepl("^[AR]", WORD_LIST), WORD_LIST, NA))
    
    #  ID WORD_LIST WORDS_A_R
    #1  1     APPLE     APPLE
    #2  2       RED       RED
    #3  3      SNOW      <NA>
    #4  4    ANKARA    ANKARA
    #5  5     RENEW     RENEW