Case-insensitive search of a list in R
Solution 1:
I would suggest the grep()
function and some of its additional arguments that make it a pleasure to use.
grep("stringofinterest",names(dataframeofinterest),ignore.case=TRUE,value=TRUE)
without the argument value=TRUE
you will only get a vector of index positions where the match occurred.
Solution 2:
Assuming that there are no variable names which differ only in case, you can search your all-lowercase variable name in tolower(names(myDataFrame))
:
match("b", tolower(c("A","B","C")))
[1] 2
This will produce only exact matches, but that is probably desirable in this case.
Solution 3:
With the stringr
package, you can modify the pattern with one of the built in modifier functions (see `?modifiers). For example since we are matching a fixed string (no special regular expression characters) but want to ignore case, we can do
str_detect(colnames(iris), fixed("species", ignore_case=TRUE))
Or you can use the (?i)
case insensitive modifier
str_detect(colnames(iris), "(?i)species")
Solution 4:
For anyone using this with %in%
, simply use tolower
on the right (or both) sides, like so:
"b" %in% c("a", "B", "c")
# [1] FALSE
tolower("b") %in% tolower(c("a", "B", "c"))
# [1] TRUE