Reputation: 21
I need help with the following R code - my code is:
best <- function(state, outcome) {
## Read outcome data
outcome <- read.csv("outcome-of-care-measures.csv", colClasses = "character") enter code here
## Check that state and outcome are valid using STOP function and
## message "invalid state" or "invalid outcome"
valid_outcomes <- c("heart attack", "heart failure", "pneumonia")
if(!state %in% state.abb){
stop("Invalid state")
}
else if (!outcome %in% valid_outcomes)
{
stop("Invalid outcome")
}
return(x)
## Return hospital name in that state with lowest 30-day death ## rate
}
It returns:
Error in best("NY", "health") : Invalid outcome
In addition: Warning message:
In if (!outcome %in% valid_outcomes) { :
the condition has length > 1 and only the first element will be used
If I use else if (any(!outcome %in% valid_outcomes)) it seems to help, but the logical condition isn't being resolved properly.
Any ideas on how to solve this issue? Thanks
Upvotes: 2
Views: 1088
Reputation: 10483
Your if condition is evaluating a vector of output whereas it is designed to take only one logical value. Try this code to see the issue:
> outcome <- c('one', 'two', 'pneumonia')
> valid_outcomes <- c("heart attack", "heart failure", "pneumonia")
> outcome %in% valid_outcomes
[1] FALSE FALSE TRUE
You see that it returns a vector of true/false values. To put them all into one condition, you can use:
if (!all(outcome %in% valid_outcomes)) { stop('blah') }
Same issue for the states that you need to fix.
Upvotes: 0