Search code examples
rfunctionfor-looplogical-operatorsscoping

Trouble getting function to return TRUE


I have some code to check to see if the input to a function is a valid US state. I have a CSV file with a State column and those are the only states I care about. So I made this code with a for loop to check if the input matches any of the states in that list, and if so, to return the value TRUE.

valid_state <- function(state) {
    CSV <- read.csv("outcome-of-care-measures.csv")
    for (i in range(length(unique(CSV$State)))) {
        if (state == unique(CSV$State)[i]) {
            return (TRUE)
        }
    }
}

All it returns is a NULL. I know that a valid state was entered just by looking at the CSV file myself. I think the problem starts when I try to introduce the problem but I don't know why. Basically, the input could only possible match one state on the list, and if it does, it should just return a logical vector with one TRUE.


Solution

  • Maybe this. It is a common mistake to forget the preceeding "1:":

    valid_state <- function(state) {
        CSV <- read.csv("outcome-of-care-measures.csv")
        for (i in 1:length(unique(CSV$State))) {
            if (state == unique(CSV$State)[i]) {
                return (TRUE)
            }
        }
    }