Reputation: 23
My function returns "character(0)" and I can't work out why. If I do it step by step in the console the result is right but not when I execute the function.
The assigment I've got is the following: Write a function called best that take two arguments: the 2-character name of a state and an outcome. The function returns the name of the hospital that has the lowest mortality rate for the specified outcome (mortality rate) in that state. The outcomes can be one of “heart attack”, “heart failure”, or “pneumonia”. Hospitals that do not have data on a particular outcome should be excluded from the set of hospitals when deciding the rankings.
The code I've got is the following:
best <- function(state, outcome) {
## Read outcome data
data <- read.csv("outcome-of-care-measures.csv", colClasses = "character", na.strings = "Not Available")
data <- data[c(2, 7, 11, 17, 23)]
names(data)[c(3:5)] <- c("heart attack", "heart failure", "pneumonia")
## Check that state and outcome are valid
if (!state %in% unique(data$State)){
stop("Invalid State")
}
if (!outcome %in% c("heart attack", "heart failure", "pneumonia")) {
stop("Invalid outcome")
}
## Return hospital name in that state with lowest 30-day death
hospital_data <- data[data$State == state, ]
min <- which.min(hospital_data$outcome)
hospital_name <- hospital_data[min, 1]
print(hospital_name)
}
Upvotes: 1
Views: 1558
Reputation: 887421
The issue is
min <- which.min(hospital_data$outcome)
and 'outcome' is passed as a string, but it is just literally using 'outcome' instead of the value passed in the function. It looks for the column 'outcome' in the data.frame and couldn't find it.
df1 <- data.frame(col1 = 1:5)
outcome <- 'col1'
df1$outcome
#NULL
df1[[outcome]]
Use [[
instead of $
min <- which.min(hospital_data[[outcome]])
Upvotes: 1