尝试%in%
如下:
foo <- function(b) {
if(0 %in% b) {
## do something
writeLines("Zero was in `b`")
}
}
> b <- 0
> foo(b)
Zero was in `b`
> b <- c(1,4,5)
> foo(b)
> b <- c(b, 0)
> foo(b)
Zero was in `b`
这里的重点是检查你感兴趣的东西(这里0
)是否包含在通过 vector 提供的项目集中b
。
对于“做其他事情”的情况,您需要foo()
使用else
子句进行扩展:
foo <- function(b) {
if(0 %in% b) {
## do something
writeLines("Zero was in `b`")
} else {
## do something else
writeLines("Zero was not in `b`")
}
}
> b <- 0
> foo(b)
Zero was in `b`
> b <- c(1,4,5)
> foo(b)
Zero was not in `b`
> b <- c(b, 0)
> foo(b)
Zero was in `b`