如果条件语句错误:“}”中的意外“}”

时间:2018-06-29 04:34:06

标签: r if-statement

rankhospital <- function(state, outcome, num = "best"){
      ## Read outcome data
      data <- read.csv("outcome-of-care-measures.csv", colClasses = "character")
      hospital <- data.frame(data[,2], #name 
                             data[,7], #state
                             data[,11], #heart attack
                             data[,17], # heart failure
                             data[,23], stringsAsFactors = FALSE) #pneumonia
      colnames(hospital) <- c("name", "state", "heart attack", "heart failure", "pneumonia")
      ## Check that state and outcome are valid
      if (!state %in% hospital[, "state"]) { stop('invalid state')} 
      else if (!outcome %in% c("heart attack", "heart failure", "pneumonia")){ stop('invalid outcome')}
      else if (is.character(num)){
        if (num == "best") {
          chosen_state <- hospital[which(hospital[, "state"] == state), ] #select the state
          chosen_outcome <- chosen_state[ , outcome] #select the outcome from the state
          best_outcome <- chosen_state[which(chosen_outcome == min(chosen_outcome, na.rm = TRUE)),]["name"]
          best_hospital <- best_outcome[order(best_outcome)][ , "name"] #sort
          best_hospital
        } 
        else (num == "worst") {
          chosen_state <- hospital[which(hospital[, "state"] == state), ] #select the state
          chosen_outcome <- chosen_state[ , outcome] #select the outcome from the state
          best_outcome <- chosen_state[which(chosen_outcome == max(chosen_outcome, na.rm = TRUE)),]["name"]
          best_hospital <- best_outcome[order(best_outcome)][ , "name"] #sort
          best_hospital
        } 
      else (is.numeric(num)) {
        if (num =< length(hospital$name){
          chosen_state <- hospital[which(hospital[, "state"] == state), ] #select the state
          chosen_outcome <- as.numeric(chosen_state[ , outcome]) #select the outcome from the state
          chosen_state[which(sort(chosen_outcome)) == num, ][,"name"]

       } 
        else (num > length(hospital$name) { stop('NA')}

     } 

    }

当我运行代码时,它会在“}”“”中抛出“错误:意外'}' else(num ==“ worst”)部分,因此如果我从其他地方更改此内容,它将崩溃并在else(is.numeric(num))处再次抛出错误。我用这段代码做错了什么?我以为If语句是这样的

  1. 如果
  2. 否则,如果
  3. 否则,如果
  4. 其他

此外,您可以像我使用的方法一样在其中添加附加的if / else语句。也许不是因为它引发了我一个错误,所以有人可以看到它有什么问题并告诉我如何解决吗?

1 个答案:

答案 0 :(得分:0)

met_conditions <- ifelse(n_weight[combination$PC, combination$PC] == 1 & n_weight[combination$RC, combination$RC] == 1, TRUE, FALSE) m[met_conditions] <- 1 else if必须与else表达式的末尾处在同一行,您之间不能有换行符。您可以使用花括号将其整洁地表达出来,例如:

if