1
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)条件?

4

2 回答 2

3

这很简单:

if any((D[i, 1] %in% e))
于 2013-07-09T10:40:42.187 回答
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
于 2013-07-09T10:44:01.040 回答