【问题标题】:OR Operator as function switchOR 运算符作为功能开关
【发布时间】:2017-11-11 09:14:15
【问题描述】:

我觉得问这个相当简单的问题有点尴尬,但我现在正在寻找几个小时,无法理解。

我正在尝试为我的功能构建一个开关:

output <- "both"

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

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

这应该产生partoneparttwo。而output &lt;- "partone" 只是partone

这怎么可能?

【问题讨论】:

  • == 适用于单个元素。您可能需要%in%greplif(any(output %in% c('both', 'partone')))

标签: r logical-operators


【解决方案1】:

使用类似的东西。

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

{cat("partone")}

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

{cat("parttwo")}

它会产生你想要的输出。

【讨论】:

    【解决方案2】:

    如果我们检查逻辑条件

    output== "both" | "partone"
    

    输出错误 == "both" | "partone" : 操作是可能的 仅适用于数字、逻辑或复杂类型

    由于我们需要检查“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'))
    

    【讨论】:

      【解决方案3】:

      此语法不正确:

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

      你可以这样写:

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

      或者像这样:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-09
        • 1970-01-01
        • 1970-01-01
        • 2015-07-08
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 2017-03-14
        相关资源
        最近更新 更多