Case-Insensitive Search of a List in R

Case-insensitive search of a list in R

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.

How to do a case-insensitive search?

try

g = c("PLD3","PLD2","PLD2ABC","DTPLD2a")
r <- 'pLd2'
r2 <- paste('^', r, '$', sep = '')
grep(r2 , g ,ignore.case = T, value=TRUE)

[1] "PLD2"

basically the meta characters ^ and $ force grep to fix the regular expression at the start and the end.

R case-insensitive %in%

Based on the comments above, I came to the relatively simple solution below:

#' Quick Search
#'
#' Quick case-insensitive search of strings in a character vector
#'
#' @param str a character vector: the values to be matched
#' @param vec a character vector: the values to be matched against
#'
#' @details Utilizes \code{data.table::`%chin%`} to rapidly complete a case-insensitive search
#' through a character vector to return a logical vector of string detections.
#' Will always return TRUE or FALSE for each position of \code{str} regardless of NA missing values
#' in either provided vector. NA in \code{str} will never match an NA value in \code{vec}.
#'
#' @return a logical vector of length \code{length(str)}
#'
#' @export
#' @importFrom data.table %chin%
#'
#' @examples
#' x <- c("apple","banana","cherry",NA)
#' "apple" %qsin% x
#' c("APPLE","BANANA","coconut", NA) %qsin% x
#'
`%qsin%` <- function(str, vec) {
tolower(str) %chin% na.omit(tolower(vec))
}

Which() case insensitive in R

The tolower function won't work on a dataframe. which is designed for vectors and matrices, and works on dataframes by converting them to matrices first. So you need to do that explicitly:

which(tolower(as.matrix(dataframe)) == "matching string", arr.ind = TRUE)

which' command in R with case insensitive

You can convert your names to upper cases

which(toupper(names(mydata)) == "COLUMN73")

Case-insensitive search of a list in R

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.

Case Insensitive Unique keeping original

You can try the code below using duplicated

x[!duplicated(tolower(x))]

turning off case sensitivity in r

There's no way to turn off case sensitivity of ==, but coercing both character vectors to uppercase and then testing for equality amounts to the same thing:

toupper(A1)
[1] "A" "A" "A" "A" "A" "A" "A"

toupper(A1)==toupper(B1)
# [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE


Related Topics



Leave a reply



Submit