如何检查矩阵的第一列是否包含向量的值

时间:2013-07-09 10:38:03

标签: r function

fn <- function(D, e) {
  for(i in 1:nrow(D)) {
    if(D[i,1] == e) {
      print("y")
    }
  }
}

fn(events, "a")

问题:events是一个2乘n的矩阵。如果不是"a",我想在c("a","b","c")中传递e,那么如何检查if(D[i,1]==e)条件?

2 个答案:

答案 0 :(得分:3)

这很简单:

if any((D[i, 1] %in% e))

答案 1 :(得分:2)

我会这样做:

x <- matrix(sample(letters, 25), ncol = 5)

> x
     [,1] [,2] [,3] [,4] [,5]
[1,] "k"  "v"  "n"  "l"  "f" 
[2,] "w"  "c"  "y"  "r"  "i" 
[3,] "u"  "p"  "o"  "q"  "j" 
[4,] "g"  "s"  "d"  "t"  "x" 
[5,] "a"  "z"  "b"  "h"  "m" 

e <- c("r", "e", "d")
apply(x, 1, function(x, e) any(x %in% e), e = e)

[1] FALSE  TRUE FALSE  TRUE FALSE