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")
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")
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"
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.