【问题标题】:R string vector error - the condition has length > 1 and only the first element will be usedR 字符串向量错误 - 条件长度 > 1 且仅使用第一个元素
【发布时间】:2016-01-02 17:07:41
【问题描述】:

我需要以下 R 代码的帮助 - 我的代码是:

best <- function(state, outcome) { 
        ## Read outcome data
        outcome <- read.csv("outcome-of-care-measures.csv", colClasses = "character") enter code here

        ## Check that state and outcome are valid using STOP function and
        ## message "invalid state" or "invalid outcome"

        valid_outcomes <- c("heart attack", "heart failure", "pneumonia")

        if(!state %in% state.abb){
                stop("Invalid state")
        }  
        else if (!outcome %in% valid_outcomes)
        {
                stop("Invalid outcome") 
        }

        return(x)
        ## Return hospital name in that state with lowest 30-day death ## rate
}

返回:

Error in best("NY", "health") : Invalid outcome
In addition: Warning message:
In if (!outcome %in% valid_outcomes) { :
   the condition has length > 1 and only the first element will be used

如果我使用 else if (any(!outcome %in% valid_outcomes)) 似乎有帮助,但逻辑条件没有得到正确解决。

关于如何解决这个问题的任何想法?谢谢

【问题讨论】:

    标签: r string conditional-statements


    【解决方案1】:

    试试这个:

     if(!any(state == data$State)) {
        stop('invalid state')
      }
    

    【讨论】:

      【解决方案2】:

      您的 if 条件正在评估一个输出向量,而它被设计为仅采用一个逻辑值。试试这个代码看看问题:

      > outcome <- c('one', 'two', 'pneumonia')
      > valid_outcomes <- c("heart attack", "heart failure", "pneumonia")
      > outcome %in% valid_outcomes
      [1] FALSE FALSE  TRUE
      

      您会看到它返回一个由真/假值组成的向量。要将它们全部归为一个条件,您可以使用:

      if (!all(outcome %in% valid_outcomes)) { stop('blah') }
      

      对于您需要修复的状态的相同问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-17
        • 1970-01-01
        相关资源
        最近更新 更多