match with language R for getting the position

前端 未结 3 1018
再見小時候
再見小時候 2021-01-19 14:32

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

相关标签:
3条回答
  • 2021-01-19 15:11

    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%

    0 讨论(0)
  • 2021-01-19 15:17

    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.

    0 讨论(0)
  • 2021-01-19 15:18

    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.

    0 讨论(0)
提交回复
热议问题