简体   繁体   中英

Lapply instead of for loop in r

I want to write the function ,that returns a 2-column data frame containing the hospital in each state that has the ranking specified in num.

Rankall that takes two arguments: an outcome name (outcome) and a hospital ranking (num). The function reads the outcome-of-care-measures.csv file and returns a 2-column data frame containing the hospital in each state that has the ranking specified in num.

rankall <- function(outcome, num = "best") {
## Read outcome data
## Check that state and outcome are valid
## For each state, find the hospital of the given rank
## Return a data frame with the hospital names and the
## (abbreviated) state name
}

head(rankall("heart attack", 20), 10)
hospital state
AK <NA> AK
AL D W MCMILLAN MEMORIAL HOSPITAL AL
AR ARKANSAS METHODIST MEDICAL CENTER AR
4
AZ JOHN C LINCOLN DEER VALLEY HOSPITAL AZ
CA SHERMAN OAKS HOSPITAL CA
CO SKY RIDGE MEDICAL CENTER CO
CT MIDSTATE MEDICAL CENTER CT
DC <NA> DC
DE <NA> DE
FL SOUTH FLORIDA BAPTIST HOSPITAL FL

My function works correct, but the last step(formating 2-column data frame) I made by the following loop:

new_data <- vector()
    for(i in sort(unique(d$State))){
        new_data <- rbind(new_data,cbind(d$Hospital.Name[which(d$State == i)][num],i))
    }
new_data <- as.data.frame(new_data)

It is correct, but i know, that it is possible to code the same loop by lapply function

My attempt is wrong:

lapply(d,function(x) x <-rbind(x,d$Hospital.Name[which(d$State == i)][num]))

How can I fix that?

I'm supposing your d data is already sorted:

new_data <- do.call(rbind,
                    lapply(unique(d$State),
                           function(state){
                              data.frame(State = state,
                                         Hospital.Name = d$Hospital.Name[which(d$State==state)][num],
                                         stringsAsFactors = FALSE)
                       }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM