Returning a particular index of a list based on another index of the same list R -
i have list below(this 1 element of list there 50 more every state)
$ak hospital.name state heartattack heartfailure pneumonia 99 providence alaska medical center ak 13.4 12.4 7.9 103 alaska regional hospital ak 14.5 13.4 8.9 102 fairbanks memorial hospital ak 15.5 15.6 9.8 106 alaska native medical center ak 15.7 11.6 11.6 100 mat-su regional medical center ak 17.7 11.4 9.0 104 yukon kuskokwim delta reg hospital ak not available 11.2 6.9 110 sitka community hospital ak not available not available 7.8 114 peacehealth ketchikan medical center ak not available 11.4 8.0 101 bartlett regional hospital ak not available 11.6 8.1 113 norton sound regional hospital ak not available not available 8.1 111 providence kodiak island medical ctr ak not available not available 8.2 115 south peninsula hospital ak not available 10.8 8.5 107 mt edgecumbe hospital ak not available not available 9.6 105 central peninsula general hospital ak not available 11.6 9.8 108 providence valdez medical center ak not available not available not available 109 providence seward hospital ak not available not available not available 112 cordova community medical center ak not available not available not available
i trying bring-out hospitals has less heartattack rate across list.
so when write function work on first element of list , call
test <- function(x){ if(x[[1]][,3] == min(x[[1]][,3])) return(head(x[[1]][1],1)) } test(statedata)
it seems work fine below warning
(warning message: in if (x[[1]][, 3] == min(x[[1]][, 3])) return(head(x[[1]][1], 1)) : condition has length > 1 , first element used) hospital.name 99 providence alaska medical center
but when try use same function code inside lapply loop through entire list element not seem work , fails below issue
result <- lapply(statedata,function(statedata) if(statedata[[1]][,3] == min(statedata[[1]][,3])) return(head(statedata[[1]][1],1)) ) error in statedata[[1]][, 3] : incorrect number of dimensions
not sure if missing lapply??
that's right because you're masking global variable statedata function parameter statedata. better way be:
statedata = lapply(statedata, function(s) { s[!is.na(as.integer(s$heartattack)),,drop=f] }) wm = which.min(sapply(statedata, function(s) min(s$heartattack))) wstate = statedata[[wm]] wstate[which.min(wstate$heartattack), "hospital"]
the first lapply remove "not available" hospitals, next sapply find worst state, , worst state used grab worst hospital in worst state.
Comments
Post a Comment