Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ifelse starting with, ends with, includes [duplicate]

Tags:

r

Is there any way to implement these conditions in ifelse statement?

df <-data.frame(Name = c("Tom","Mary","Tim","Chris") )

ifelse(name starting with T, "YES", "NO")
ifelse(name include i, "YES", "NO")
ifelse(name ends with s, "YES", "NO")
like image 738
joerna Avatar asked Sep 12 '25 22:09

joerna


1 Answers

You can use grepl() (see help(grepl) and help(regex)):

ifelse(grepl('^T', df$Name), 'YES', 'NO')
ifelse(grepl('i', df$Name), 'YES', 'NO')
ifelse(grepl('s$', df$Name), 'YES', 'NO')

which results in the following output (easily checkable):

> ifelse(grepl('^T', df$Name), 'YES', 'NO')
[1] "YES" "NO"  "YES" "NO" 
> ifelse(grepl('i', df$Name), 'YES', 'NO')
[1] "NO"  "NO"  "YES" "YES"
> ifelse(grepl('s$', df$Name), 'YES', 'NO')
[1] "NO"  "NO"  "NO"  "YES"

Details

grepl() returns a logical vector the same length as the vector that is the function's second argument, returning TRUE where the regular expression of the function's first argument is present and FALSE for elements where the expression is not found.

In regular expressions, typically, and in R in particular, ^ matches the first character and $ matches the last. So, ^T is a regular expression looking for a string that begins with T while s$ is a regular expression looking for a string that ends in s.

like image 191
duckmayr Avatar answered Sep 14 '25 11:09

duckmayr