【发布时间】:2017-01-29 11:42:12
【问题描述】:
作为 Coursera 数据专业化的一部分,我必须分析美国医院的数据集并编写一个具有以下内容的函数:
- 输入:说明名称和原因(心脏病发作、心力衰竭或肺炎)
- 输出:给定状态下给定原因死亡率最低的医院
该函数应执行以下操作:
- 加载数据集
- 检查输入的状态和原因(结果)是否有效
- 返回死亡率最低的医院,如果平则按字母顺序返回
我希望将医院的名称作为长度为 1 的字符的向量,但我得到的是“字符 (0)”作为输出
所需输出示例:
best("TX", "pneumonia")
[1] "UNIVERSITY OF TEXAS HEALTH SCIENCE CENTER AT TYLER"
实际输出示例:
best("TX", "pneumonia")
character(0)
请帮我看看我的代码哪里出了问题。非常感谢
这是我的代码:
## This function returns the best hospital in a state, given the disease types
## based on its mortality rate in 30-day period
best <- function(state, outcome) {
## calling data
outcomedata <- read.csv("outcome-of-care-measures.csv", colClasses = "character")
## putting needed data into data frame
outcomedf <- as.data.frame(cbind(outcomedata[, 2], outcomedata[, 7],
outcomedata[, 11], outcomedata[, 17],
outcomedata[, 23]),
stringsAsFactors = FALSE)
colnames(outcomedf) <- c("hospital", "state", "heart attack", "heart failure", "pneumonia")
## Checking valid state
if(!state %in% outcomedf[, "state"]){
stop('invalid state')
## Checking valid outcome
}
else if(!outcome %in% c("heart attack", "heart failure", "pneumonia")){
stop('invalid outcome')
## Calling out best hospital
}
else {
## Extracting data for given state
obs_in_called_states <- which(outcomedf[, "state"] == state)
obs_in_states_extract <- outcomedf[obs_in_called_states, ]
oi <- as.numeric(obs_in_states_extract[, eval(outcome)])
## getting the min value
minvalue <- min("oi", na.rm = TRUE)
result <- obs_in_states_extract[, "hospital"][which(oi == minvalue)]
output <- result[order(result)]
}
return(output)
}
【问题讨论】:
-
我想知道你有没有 seach the internet first。关于如何解决这个问题的问题和答案有很多。请阅读How to Ask
-
您能否简化您的问题并仅关注导致您出现问题的部分?请模拟一些显示您的问题的数据并提出。
标签: r