0

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?

3
  • What is num? Please show a small reproducible example Commented Oct 5, 2016 at 11:23
  • @akrun added, check it once more,please Commented Oct 5, 2016 at 11:28
  • I think the purpose of this coursera excersice was to use the split and lapply functions. Commented Oct 5, 2016 at 13:03

1 Answer 1

1

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)
                       }))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.