how to check if a string exsits in a column in R code example

Example 1: check if column contains string in vector r

v <- c('a','b','c','e')

'b' %in% v
## returns TRUE

match('b',v)
## returns the first location of 'b', in this case: 2

Example 2: check if a string is contained in a column R

fruit <- c("apple", "banana", "pear", "pinapple")     # [1] TRUE
identical(str_detect(fruit, "a"), grepl("a",fruit))   # [1] TRUE
identical(str_detect(fruit, "^a"), grepl("^a",fruit)) # [1] TRUE
identical(str_detect(fruit, "a$"), grepl("a$",fruit)) # [1] TRUE
identical(str_detect(fruit, "b"), grepl("b",fruit))   # [1] TRUE
identical(str_detect(fruit, "[aeiou]"), grepl("[aeiou]",fruit)) # [1] TRUE

Tags:

Misc Example