简体   繁体   中英

'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 ?

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)]

您可以将您的姓名转换为大写

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM