I have looked through all the posts i could find on dplyr::arrange() or order() argument lengths differ errors, but have not found an explanation.
Im trying to make a function best() that can return the lowest rated value from a dataframe of hospital outcomes (dfout). When i copy the code straight into R it runs without an error, returning the hospital name with the lowest mortality rate. Only when i call it as a function does it say "Error in order(State, outcome, Hospital) : argument lengths differ"
The function: (note i used capitalized names for colnames and non capitalized for function variables)
best <- function(state, outcome){
colnames(dfout) <- c("Hospital", "State", "Heartattack", "Heartfailure", "Pneumonia")
##Return hospital name with lowest 30 day mortality rate
arranged <- arrange(dfout, State, outcome, Hospital) ## arrange hospitals by state, mortality rate in the specified outcome in best() and alphabetically for the ties.
arranged1 <- arranged[arranged$State == state,] ## take the part of the ordered list where state = the state specified in best()
arranged1$Hospital[1]
Now if i call best("TX", Heartattack) i get "Error in order(State, outcome, Hospital) : argument lengths differ", but if i simply run the code and replace state and outcome with "TX" and Heartattack i get a hospital, like this
##Return hospital name with lowest 30 day mortality rate arranged <- arrange(dfout, State, Heartattack, Hospital) ## arrange hospitals by state, mortality rate in the specified outcome in best() and alphabetically for the ties. arranged1 <- arranged[arranged$State == "TX",] ## take the part of the ordered list where state = the state specified in best() arranged1$Hospital[1] [1] "CYPRESS FAIRBANKS MEDICAL CENTER"
My question is really: how can the function not work, when copying the same code into the command line with the variables put in works.