forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrankall.R
More file actions
45 lines (33 loc) · 1.28 KB
/
rankall.R
File metadata and controls
45 lines (33 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
rankall <- function(outcome, num = "best") {
# Read outcome data
out_dt <- data.table::fread('outcome-of-care-measures.csv')
outcome <- tolower(outcome)
if (!outcome %in% c("heart attack", "heart failure", "pneumonia")) {
stop('invalid outcome')
}
# Renaming Columns to be less verbose and lowercase
setnames(out_dt
, tolower(sapply(colnames(out_dt), gsub, pattern = "^Hospital 30-Day Death \\(Mortality\\) Rates from ", replacement = "" ))
)
# Columns indices to keep
col_indices <- grep(paste0("hospital name|state|^",outcome), colnames(out_dt))
# Filtering out unnessecary data
out_dt <- out_dt[, .SD ,.SDcols = col_indices]
# Find out what class each column is
# sapply(out_dt,class)
# Change outcome column class
out_dt[, outcome] <- out_dt[, as.numeric(get(outcome))]
if (num == "best"){
return(out_dt[order(state, get(outcome), `hospital name`)
, .(hospital = head(`hospital name`, 1))
, by = state])
}
if (num == "worst"){
return(out_dt[order(get(outcome), `hospital name`)
, .(hospital = tail(`hospital name`, 1))
, by = state])
}
return(out_dt[order(state, get(outcome), `hospital name`)
, head(.SD,num)
, by = state, .SDcols = c("hospital name") ])
}