onhalu
onhalu

Reputation: 745

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

Upvotes: 0

Views: 263

Answers (2)

Duck
Duck

Reputation: 39595

You can also use base R with substring() function:

#Create condition
cond1 <- substr(DF$WORD_LIST,1,1)=='A' | substr(DF$WORD_LIST,1,1)=='R'
#Create var
DF$WORDS_A_R <- NA
DF$WORDS_A_R[cond1]<-DF$WORD_LIST[cond1]

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

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388907

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

Upvotes: 2

Related Questions