如何根据用户输入值计算最小金额

时间:2016-05-14 06:23:34

标签: r min

这里我得到包含4706个观察结果的csv文件,然后我需要建立一个“最好的宿主”功能,根据状态和关键词用户输入来计算不同医院的最小心脏病发作,心力衰竭,肺炎发病率state,然后按升序返回第一个hosiptal名称。

下面是我写的部分代码,但我仍然坚持如何根据状态用户输入计算最小值。例如,如果用户输入NY,则找到最小心脏病发作率,然后返回NY中的医院名称

best<-function(state,outcome){
a<-read.csv("outcome-of-care-measures.csv",na.string="Not Available")
if(!state %in% a[,7])
print ("invalid state")
if(outcome=="heart attack")
bd<-suppressWarnings(as.numeric(as.character(a[,11])))
.... 
}

数据样本可能如下:

Hospital   State    deaths in heart attack   deaths in heart failure 

L hospital  NY       10.1                     10.2

S hospital  NY       10.2                     10.5

M hospital  AZ       18.0                     14.5

Z hospital  AZ       14.0                     14.5

预期结果是:

best("NY", "heart attack")

[1] L Hospital

best("AZ", "heart failure")

[1] "M Hostpital"

请注意,文件中的心脏病发作率为factor变量,因此我需要将其转换为numeric,如何继续?谢谢!

1 个答案:

答案 0 :(得分:0)

也许这有帮助

best <- function(dat, St, keyword){
  nm1 <- grep(keyword, names(dat))
  i1 <- dat[["State"]] == St
  Subdat <- dat[i1,]
  Subdat[["Hospital"]][which.min(Subdat[,nm1])]
 }

best(df1, "NY", "heart attack")
#[1] "L hospital"
best(df1, "AZ", "heart failure")
#[1] "M hospital"

注意:不清楚哪个列是heart attack rate

数据

df1 <- structure(list(Hospital = c("L hospital", "S hospital", 
"M hospital", 
"Z hospital"), State = c("NY", "NY", "AZ", "AZ"), 
`deaths in heart attack` = c(10.1, 
10.2, 18, 14), `deaths in heart failure` = c(10.2, 10.5, 14.5, 
14.5)), .Names = c("Hospital", "State", "deaths in heart attack", 
"deaths in heart failure"), class = "data.frame", row.names = c(NA, -4L))