Paige Kemp
Paige Kemp

Reputation: 97

How to check presence of vowel in a string? And return 1 or 0?

I have a set of words in a column and I want to check the presence/absence of an "o" or "u" in them. If the word has an "o" or "u" I want a new column with the "1" and if it doesn't I want a "0".

Example of how the data looks now:

  ID    Word    
  1     rabbit 
  2     horse
  3     tunnel
  4     table

This is how I want the data to look:

ID    Word      Subset_Vowel
1     rabbit          0  
2     horse.          1
3     tunnel          1
4     table           0

I tried this code: DryRun_data_df$Subset_Vowel <- ifelse(str_detect(words, "o" || "u"), 1, 0)

But here was the error: Error in "o" || "u" : invalid 'x' type in 'x || y'

I am also open to other ways on how to check the absence/presence of "o" and "u"

Thanks for all your help in advance!!

Upvotes: 2

Views: 279

Answers (1)

akrun
akrun

Reputation: 887501

Replace the || with | and then coerce the logical to binary with as.integer (or +)

library(stringr)
df1$Subset_Vowel <- as.integer(str_detect(df1$Word, "o|u"))
df1
#  ID   Word Subset_Vowel
#1  1 rabbit            0
#2  2  horse            1
#3  3 tunnel            1
#4  4  table            0

Or in base R with grepl

df1$Subset_Vowel <- +(grepl("o|u", df1$Word))

data

df1 <- structure(list(ID = 1:4, Word = c("rabbit", "horse", "tunnel", 
"table")), class = "data.frame", row.names = c(NA, -4L))

Upvotes: 4

Related Questions