我有一个如下所示的列表(这只是列表中的一个元素,每个州还有50个元素)
$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
我正试图推出名单中HeartAttack率较低的医院。
所以当我编写一个函数来处理这个列表的第一个元素并调用
时 test <- function(x){
if(x[[1]][,3] == min(x[[1]][,3]))
return(head(x[[1]][1],1))
}
test(statedata)
似乎工作正常,但有以下警告
(Warning message:
In if (x[[1]][, 3] == min(x[[1]][, 3])) return(head(x[[1]][1], 1)) :
the condition has length > 1 and only the first element will be used)
Hospital.Name
99 PROVIDENCE ALASKA MEDICAL CENTER
但是,当我尝试在lapply中使用相同的函数代码循环遍历整个列表元素时,它似乎无法正常工作并因以下问题而失败
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
不确定我是否遗漏了lapply的内容?
答案 0 :(得分:0)
这是正确的,因为你用函数参数声明数据掩盖了全局变量声明数据。更好的方法是:
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"]
第一个lapply是删除&#34; Not Available&#34;医院,接下来的事情就是找到最糟糕的状态,然后最坏的状态被用来抢到处境最差的最差的医院。