IAMTubby
IAMTubby

Reputation: 1677

'which' command in R with case insensitive

I am trying to find indexes within a data frame which holds a certain string. But I would like my string to be case insensitive. Say, I want to search for column number in my data frame called COLUMN73 and I expect it to return 73 because it is the seventy third column. I have,

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

Is it possible to make my search string case insensitive so as to get 73 even if I search for say, CoLumN73 ?

Upvotes: 1

Views: 3280

Answers (3)

Carl Witthoft
Carl Witthoft

Reputation: 21532

Completely edited, with a correction for Will's code. Thanks to David Arenburg for pointing this out.

x <- rep(c("col7", "COL73", "Col17","COLUMN73", "CoL73", "cOl73"),1e4)
scriven<- function(x) grepl("COLUMN73", x, ignore.case=TRUE)
will<-function(x) which(toupper((x)) == "COLUMN73")
microbenchmark(scriven(x),will(x))
Unit: milliseconds
       expr      min       lq   median       uq      max neval
 scriven(x) 30.55911 33.04852 34.91243 37.01039 39.59833   100
    will(x) 26.10728 26.47967 27.21592 28.76291 30.46163   100

Upvotes: 0

Rich Scriven
Rich Scriven

Reputation: 99351

You can index it with grepl by using the ignore.case argument

x <- c("col7", "COL73", "Col17", "CoL73", "cOl73")
grepl("col73", x, ignore.case=TRUE)
# [1] FALSE  TRUE FALSE  TRUE  TRUE

Similarly, grep returns the numeric index

grep("col73", x, ignore.case=TRUE)
# [1] 2 4 5

For data frame column subsets

df[grepl("col73", names(df), ignore.case=TRUE)]

Upvotes: 7

You can convert your names to upper cases

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

Upvotes: 6

Related Questions