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)
条件?
这很简单:
if any((D[i, 1] %in% e))
我会这样处理它:
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