match with language R for getting the position

白昼怎懂夜的黑 提交于 2019-12-31 01:40:06

问题


I am using match for getting if an element is in a list. For example my list is:

  c("a","b","h","e"...) and so on

if I want to see if element h is in the list I am using match in this way:

  if ("h" %in% v){do something}

How I can get the position of where it finds the element in the list? Thanks


回答1:


If you want to know the position use which

l <- c("a","b","h","e")
which(l=='h') 
[1] 3   # It'll give you the position, 'h' is the third element of 'l'

Note that l is a vector, not a list as you mentioned.




回答2:


The which function would tell you where in a vector an item would "match". The %in% will return a logical vector of the same length as its first argument, and if will only look at the first logical value so will not work well by itself. You could do this:

if( any("h" %in& v) ) { do something }

The any function allows you to "collapse" the result of %in%




回答3:


If you want to know the position, use match:

l <- c("a","b","h","e")
match("h", l)

It won't make any different here, but generally it will be much faster.



来源:https://stackoverflow.com/questions/12786005/match-with-language-r-for-getting-the-position

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