mercredi 30 janvier 2019

(R) How to transform string input in a function to a variable?

I want to make a function in which you can input a string of text. Then I want this string input to correspond to a variable inside my function. However, I do not know how to approach this.

The goal is to order a data frame based on a specific variable in the data frame. But, the user can input an abstraction of this variable by inputting a string. For example, the variable name is 'attack', for which the user can input the text "heart attack" when calling the function.

best <- function(state, outcome) {

hospData <- read.csv(paste(getwd(), "/R_ProgAssignment3-data/outcome-of-care-measures.csv", sep=""));

    stateSet <- subset(hospData, State == state);
    attach(stateSet);

# translates input string to outcome variable based on type of disease
if (outcome == "heart attack") { outcome <- attack; }
if (outcome == "heart failure") { outcome <- failure; }
if (outcome == "pneumonia") { outcome <- pneum; }

    #orders the state subset based on the outcome specified above
    stateSet <- arrange(stateSet, outcome);
    detach(stateSet);

    #prints the first row of the state subset with corresponding hospital and ordered mortality rate (e.g. lowest first)
    stateSet[1, c("Hospital.Name", outcome)];

}

As such, in the code above, the user can specify which state he or she wants to analyze, and the disease he wants data for, for example by inputting best("TX", "heart attack"), "failure" or "pneumonia", Where TX is the abbreviation for Texas in the dataset hospData. This text has to correspond to a variable in the data frame, which are respectively 'attack', 'failure' and 'pneum', since I want to sort the data frame for this variable.

Finally, I want to show the hospital with the lowest mortality rate in the final code line.

I think the problem lies in the if-conditions for e.g. outcome <- attack, which probably simply copies the content of either hospData$attack or stateSet$attack (another question here, how to link only the data from the subset?) to the variable 'outcome'.

To summarize, how can I recode a string input to the correct variable in the data frame, so I can sort the data frame for the specific variable?

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire