问题目标:寻找一个州最好的医院
需要的数据文件: outcome-of-care-measures.csv
说明 我正在处理美国不同州的医院数据。 csv文件包含有关4,000多家医院的30天死亡率和心脏病发作,心力衰竭和肺炎的再住院率的信息。
我想编写一个名为“ best”的函数,该函数带有两个参数:州名的2个字符的缩写(例如,纽约州为“ NY”)和结果名称。该函数读取'outcome-of-care-measures.csv'文件,并返回一个字符向量,其中包含在该状态下指定结果的30天死亡率最高(即最低)的医院名称。医院名称是csv文件中Hospital.Name变量中提供的名称。结果可能是“心脏病发作”,“心力衰竭”或“肺炎”之一。没有特定结果数据的医院在确定排名时应排除在医院之外
该函数应检查其参数的有效性。如果将无效状态值传递到最佳状态,则该函数应通过stop函数引发错误,并显示准确的消息“无效状态”。如果将无效的结果值传递给最佳值,则该函数应通过stop函数引发错误,并显示准确的消息“无效结果”。
我编写的代码:
best <- function(state,outcome) {
df <- read.csv("outcome-of-care-measures.csv")
df1 <- df[ ,c(2,7,11,17,23)] # column numbers correspond to the columns of interest from the entire csv file
table <- split(df1,df1$State)
if (outcome == "heart attack") {
n = 3
} else if (outcome == "heart failure") {
n = 4
} else if (outcome == "pneumonia") {
n = 5
} else {
stop("Invalid Outcome")
}
min.val <- min(table$state[,n],na.rm = TRUE)
row.no <- which(table$state[,n] == min.val)
print(table$state[1,row.no])
}
错误
best("TX", "heart failure")
NULL
Warning message:
In min(table$state[, n], na.rm = TRUE) :
no non-missing arguments to min; returning Inf