mercredi 21 janvier 2015

R Scoping/Structural Difficulties

When num =="worst", the function is supposed to be able to retrieve the last row in the data.frame, ha1. However I can't do an if statement like if (num = "worst"), because to get the last row I have to do tail(ha1,1). ha1 is outside the scope of the if statement. Can anyone offer any ways around this? I know there is probably a simple solution I just can't figure it out.



rankhospital <- function(state,outcome,num)

{
if (num == "best")
{
num <- 1

}


setwd('C:\\Users\\Admin\\Desktop\\R\\R')
readFile = read.csv("outcome-of-care-measures.csv", colClasses = "character")

State = readFile[, "State"]
Hospital.Name = readFile[, "Hospital.Name"]
Heart.Attack = readFile[, 11]
Heart.Failure = readFile[, 17]
Pneumonia = readFile[, 23]

#create new Data.Frame with relevant data.
my.data = data.frame(Heart.Attack, Heart.Failure, Pneumonia, State, Hospital.Name)

#You need to first identify the state, then read all those entities
#into a dataframe of ascending order of mortality for columns,
#then return the hospital associated with the selected number.

ha1 <- data.frame(my.data[,1],my.data[,5])
ha1 <- data.frame(ha1, my.data[4])

ha1 <- rapply(ha1,as.character,classes = "factor",how = "replace")


ha1 <- data.frame(lapply(ha1, as.character), stringsAsFactors=FALSE)
colnames (ha1)[1] <- "Mortality"
colnames (ha1)[2] <- "Hospital"

ha1[ha1 == "Not Available"] <- NA
ha1 <- na.omit(ha1)
ha1 <- ha1[ha1$State == state,]
rownames(ha1) <- NULL


if(nrow(ha1) < num){
stop("NA")
}


if(outcome == "pneumonia")
{
ha1 <- data.frame(my.data[,2],my.data[,5])
ha1 <- data.frame(ha1, my.data[4])

ha1 <- rapply(ha1,as.character,classes = "factor",how = "replace")


ha1 <- data.frame(lapply(ha1, as.character), stringsAsFactors=FALSE)
colnames (ha1)[1] <- "Mortality"
colnames (ha1)[2] <- "Hospital"

ha1[ha1 == "Not Available"] <- NA
ha1 <- na.omit(ha1)
ha1 <- ha1[ha1$State == state,]
rownames(ha1) <- NULL

if(nrow(ha1) < num){
stop("NA")
}


}

if(outcome == "heart failure")
{

ha1 <- data.frame(my.data[,3],my.data[,5])
ha1 <- data.frame(ha1, my.data[4])

ha1 <- rapply(ha1,as.character,classes = "factor",how = "replace")
ha1 <- data.frame(lapply(ha1, as.character), stringsAsFactors=FALSE)
colnames (ha1)[1] <- "Mortality"
colnames (ha1)[2] <- "Hospital"

ha1[ha1 == "Not Available"] <- NA
ha1 <- na.omit(ha1)
ha1 <- ha1[ha1$State == state,]
rownames(ha1) <- NULL

if(nrow(ha1) < num){
stop("NA")
}

}
return(ha1[num,])
}

Aucun commentaire:

Enregistrer un commentaire