Best option to search for characters in a column using R

Viewed 122

I have a df with column which contains different codes (ICD-10). The column contains codes which consists of 4 alpha numeric characters. I want to search for specific codes based on just the first two characters. For example if this is the column

codes = c("s001", "s1234", "s4g6", "T002", "T191","t985","s761","t17.5")

and I want all those rows where it contains S0, S1, T0, T9, T1 and assign it one and 0 if not present. I previously have used %like% with case_when. However, I would like to know if there an efficient way to do this in R.Thanks

5 Answers

Use grepl() to test for a regular expression and return true for any string that starts with s0, s1, T0, T1, T9 and otherwise false. Then ifelse() to take that vector of TRUEs and FALSEs and assigned 1 for the TRUEs, otherwise 0.

codes <- c("s001", "s1234", "s4g6", "T002", "T191","t985","s761","t17.5")

ifelse(grepl("^s[01]|^T[019]", codes), 1, 0)

Output:

[1] 1 1 0 1 1 0 0 0

Can also do:

as.numeric(grepl("^s[01]|^T[019]", codes))

We can use

+(grepl("^s[01]|^T[019]", codes))
[1] 1 1 0 1 1 0 0 0

We could define a pattern you want to detect and then use str_detect and assign 1 to TRUE and 0 to FALSE:

library(dplyr)
library(stringr)

# your dataframe with codes column
df <- data.frame(codes = c("s001", "s1234", "s4g6", 
                              "T002", "T191","t985",
                              "s761","t17.5"))

# define what you want to search for
search_pattern <- "S0|S1|T0|T9|T1"

# check with `str_detect`
df %>% 
    mutate(check = ifelse(str_detect(df$codes, search_pattern)==TRUE, 1, 0)) 

Output:

  codes check
1  s001     0
2 s1234     0
3  s4g6     0
4  T002     1
5  T191     1
6  t985     0
7  s761     0
8 t17.5     0

Another option with grepl

> +grepl("^([sT][01]|T9)", codes)
[1] 1 1 0 1 1 0 0 0

You can also use the substring approach. Extract only first 2 characters from the codes using substr and compare it against the correct_values.

codes = c("s001", "s1234", "s4g6", "T002", "T191","t985","s761","t17.5")

correct_values <- c("s0", "s1", "T0", "T9", "T1")

as.integer(substr(codes, 1, 2) %in% correct_values)
#[1] 1 1 0 1 1 0 0 0
Related