Если условный оператор Ошибка: неожиданно '}' в "}" - PullRequest
0 голосов
/ 29 июня 2018
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 == "худший"), поэтому, если я изменю это значение if from else, оно выйдет из строя и снова выдаст мне ошибку в else (is.numeric (num)). Что я сделал не так с этим кодом? Я думал, что если утверждение идет так * 1002

  1. Если
  2. еще, если
  3. иначе, если
  4. еще

Кроме того, вы можете добавить к ним дополнение If / else, например, как я использовал .. Может, нет, так как это вызывает у меня ошибку, кто-нибудь может увидеть, что с ним не так, и сказать мне, как решить?

1 Ответ

0 голосов
/ 29 июня 2018

else if и else должны находиться на той же строке, что и конец выражения if, между ними не должно быть новой строки. Вы можете выразить это аккуратно, используя фигурные скобки, например ::1004

x = 3

# This doesn't work
if (x == 2) { print("x is 2") }
else if (x == 3) { print("x is 3") }
else { print("x is something else")}

# This does, else if is on the same line as the end of the
#   if expression
if (x == 2) { 
    print("x is 2") 
} else if (x == 3) { 
    print("x is 3") 
} else { print("x is something else")}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...