4

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")
joerna
  • 435
  • 1
  • 6
  • 13
  • 2
    `?startsWith` `?grepl` `?endsWith` - as per https://stackoverflow.com/questions/31467732/does-r-have-function-startswith-or-endswith-like-python - which is practically a duplicate. – thelatemail Oct 31 '17 at 01:01
  • This past post didn't have ifelse example, and I couldn't figure out how to implement in ifelse. – joerna Oct 31 '17 at 05:05

1 Answers1

6

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.

duckmayr
  • 16,303
  • 3
  • 35
  • 53