Back to Blog
Magic liss ilike7/19/2023 That's what we need, a vector of logical. Since %like% is just an infix operator for the like function (in data.table, at least), I'm using the latter (pre-fix version) here for clarity.when using dplyr, it's probably better to use its if_else, as this version better guards against different class outputs (as well as some other issues with base ifelse).I'm converting your SQL-esque patterns to regex here.You can sapply on the patterns and do row-summing to find what you need. Mutate(group = case_when(fruits %ilike% "apple|avocado" ~ "group 1",įruits %ilike% "banana|grape" ~ "group 2", Of course, case_when() is a good alternative to nested ifelse() as suggested by r2evans: mydata %>% %ilike% will also match the word Apple (with a capital A). %ilike% is a new convenience functions which is for case-insensitive pattern matching and which became available with data.table v1.12.4 (on CRAN since ). Note that %ilike% has been used instead of %like%. Therefore, % to indicate an arbitray number of arbitrary characters is not required. So, group 1 matches any string where either apple or avocado appears anywhere in the string. Ifelse(fruits %ilike% "banana|grape", "group 2", "group 3"))) Mutate(group = ifelse(fruits %ilike% "apple|avocado", "group 1", Alternation is expressed by vertical bar: library(data.table) Data.table's like() function and its %like%, %ilike%, and %flike% operator versions only accept a single pattern parameter but you can use alternation in a regular expression.
0 Comments
Read More
Leave a Reply. |