OR 运算符作为功能开关

OR Operator as function switch

问这个相当简单的问题让我感到有点尴尬,但我已经搜索了几个小时了,还是想不通。

我正在尝试为我的函数构建一个开关:

output <- "both"

if (output== "both" | "partone")
{cat("partone")}

if (output=="both" | "parttwo")
{cat("parttwo")}

这应该会产生 partoneparttwo。而 output <- "partone" 只是 partone

这怎么行?

此语法不正确:

if (output== "both" | "partone")
{cat("partone")}

你可以这样写:

if (output == "both" || output == "partone")
{cat("partone")}

或者像这样:

if (output %in% c("both", "partone"))
{cat("partone")}

使用类似这样的东西。

if (output %in% c("both","partone"))

{cat("partone")}

if (output %in% c("both","parttwo"))

{cat("parttwo")}

它将产生您想要的输出。

如果我们检查逻辑条件

output== "both" | "partone"

Error in output == "both" | "partone" : operations are possible only for numeric, logical or complex types

因为我们需要检查 'both' 或 'partone',请在 vector 字符串元素

上使用 %in%
output %in% c('both', 'partone')
#[1] TRUE

现在,创建一个可重复使用的函数

 f1 <- function(out, vec) {
         if(out %in% vec) cat(setdiff(vec, 'both'), '\n')
}
output <- 'both'
f1(output, c('both', 'partone'))
#partone 
f1(output, c('both', 'parttwo'))
#parttwo 

output <- 'partone'
f1(output, c('both', 'partone'))
#partone 
f1(output, c('both', 'parttwo'))