R编程课程第4周作业[已关闭]

vnzz0bqm  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(80)

已关闭此问题为not reproducible or was caused by typos。它目前不接受回答。

此问题是由打印错误或无法再重现的问题引起的。虽然类似的问题可能是on-topic在这里,这一个是解决的方式不太可能帮助未来的读者。
昨天关门了。
Improve this question

我无法得到写出来的答案,请帮助!

此数据来自Programming Assignment 3问题#3

rankhospital<-function(state, outcome, num = "best") { 
## Read outcome data 
  
  data <- read.csv("outcome-of-care-measures.csv", colClasses = "character")
  
  df <- cbind(data[, 2], data[, 7], data[, 11], data[, 17], data[, 23])
  
  colnames(df) <- c("hospital", "state", "heart attack", "heart failure", "pneumonia")
  
## Check that state and outcome are valid 
  
  listoutcomes = c("heart attack", "heart failure", "pneumonia")
    
  if(outcome %in% listoutcomes == FALSE){
    stop("invalid outcome")
  }
  
  if(state %in% df[,"state"] == FALSE) {
    stop("invalid state")
  }
  
## Return hospital name in that state with the given rank 
## 30-day death rate
  
  df2 <- df[order(df[,"hospital"], decreasing = FALSE), ]
  df2 <- df[order(df[outcome], decreasing = FALSE), ]
  
  outcomes <- (df2[outcome])

  if( num == "best" ) {
    rowNum <- which.min(outcomes)
  } 
  
  else if( num == "worst" ) {
    rowNum <- which.max(outcomes)
    
  }
  else if (is.numeric(x = num)) {
    (num < 1 || num > nrow(df2[state])) 
      return(NA)
      
    
  } else {
    (rowNum <- num)
      
    }

  df2[rowNum,...]
}

当你输入:
rankhospital(“TX”,“heart failure”,4)
我得到了NA,但正确的答案是BRR。我什么都试过了。删除所有“不可用”行肯定有问题。但我找不到正确的密码来删除它们。

cbjzeqam

cbjzeqam1#

我希望理解你的代码,你的期望是得到在给定状态下结果最好/最差/第n的医院,所以在rankhospital("TX","heart failure",4)中,期望输出应该是TX状态下心力衰竭率第四低的医院。
所以请尝试运行代码如下:

rankhospital<-function(state, outcome, num = "best") { 
## Read outcome data 
  
  data <- read.csv("outcome-of-care-measures.csv", colClasses = "character")
  
  df <- cbind(data[, 2], data[, 7], data[, 11], data[, 17], data[, 23])
  
  colnames(df) <- c("hospital", "state", "heart attack", "heart failure", "pneumonia")
  
## Check that state and outcome are valid 
  
  listoutcomes = c("heart attack", "heart failure", "pneumonia")
    
  if(outcome %in% listoutcomes == FALSE){
    stop("invalid outcome")
  }
  
  if(state %in% df[,"state"] == FALSE) {
    stop("invalid state")
  }
  
## Return hospital name in that state with the given rank 
## 30-day death rate
  
  df2 <- df[df['state']==state,]
  df2 <- df2[order(df2[outcome], decreasing = FALSE), ]
  
  outcomes <- (df2[outcome])

  if( num == "best" ) {
    rowNum <- which.min(outcomes)
  } 
  
  else if( num == "worst" ) {
    rowNum <- which.max(outcomes)
    
  }
  else if (is.numeric(x = num)) {
    (num < 1 || num > nrow(df2)) 
      return(NA)
      
    
  } else {
    (rowNum <- num)
      
    }

  df2[rowNum,...]
}

希望对你的问题有帮助。

相关问题