'which' command in R with case insensitive

两盒软妹~` 提交于 2019-12-13 00:41:34

问题


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 ?

Thanks.


回答1:


You can convert your names to upper cases

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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/27085620/which-command-in-r-with-case-insensitive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!