r - How to subset a row from list based on condition -
i have data.table outcome, has column called hospital. , column called state. outcome has been sorted already. want subset nth hospital each state(if there's not nth returns na state). try solve below way.(since homework, showed third branch causes mistake).
rankall <- function(out, num = "best"){ outcome <- readdata(outcome = out) //returns data.table sorted rate ... outcome <- lapply(outcome, function(x) ifelse(num <= nrow(x), x[num,], c(na,na))) outcome <- rbindlist(outcome) } the original outcome like
> data hospital state 1: nyu hospitals center ny 2: doylestown hospital pa 3: avera heart hospital of south dakota llc sd 4: glendale adventist medical center ca 5: waterbury hospital ct --- 2716: desert springs hospital nv 2717: 3 rivers community hospital or 2718: robert wood johnson university hospital @ rahway nj 2719: laredo medical center tx 2720: medical center south arkansas ar and first , second branch produce right result, like
> head (data) hospital state 1: na ak 2: crestwood medical center al 3: arkansas heart hospital ar 4: mayo clinic hospital az 5: glendale adventist medical center ca 6: st marys hospital , medical center co > nrow(data) [1] 54 however, third condition couldn't work. produce error
error in rbindlist(outcome) : item 1 of list input not data.frame, data.table or list and after debugging found out outcome after condition like(which caused error in last step)
$ak [1] na $al $al[[1]] [1] "highlands medical center" differs first 2 like...
> head(data,2) $ak hospital state 1: providence alaska medical center ak $al hospital state 1: crestwood medical center al so wonder what's wrong third branch. me out, thank much!!!
by way, wonder if refer variable same name of another's. such when called readdata, need pass argument called outcome, prevents me use name argument of rankall function(i use out instead). know in java this.outcome help, how in r.
thank vivek's help, have figured out now. first mis-performance of third branch. it'll work if first convert numto number using as.numeric(num). think it's because num regarded character(since has possible value of "best" , "worst") caused mistake. second regarding naming space strange. though not having performed in own test, work after vivek answer question. so, means can use following code, , r right result.
rankall <- function(outcome, num = "best"){ outcome <- readdata(outcome = outcome)
Comments
Post a Comment