Home > other >  Writing a for loop function that returns boolean values
Writing a for loop function that returns boolean values

Time:11-18

I'm trying to write a function that takes an input vector, v, and returns a vector of the same length whose elements are boolean values indicating whether or not the corresponding element of the input vector indicates the variable homelessness. The function should loop over elements of v and uses the homeless vector to flag those elements of v that indicate the arrestee is homeless

I keep getting an error saying "object 'n' not found"

I've tried changing the ith variable to flag_homeless to no success.

flag_homeless <- function(v) 
    n <- length(v)
        homeless <- rep(FALSE, n)
            for (i in 1:n) {
                    if (v[i] == "No Permanent Address")  {
                        homeless[i] <- TRUE }
        }
        return(homeless)

CodePudding user response:

You could use another pair of braces for your function call. It's difficult to understand the scope of flag_homeless otherwise.

flag_homeless <- function(v) {
    n <- length(v)
    homeless <- rep(FALSE, n)
    for (i in 1:n) {
         if (v[i] == "No Permanent Address")  {
             homeless[i] <- TRUE }
    }
    return(homeless)
}

CodePudding user response:

Because R is vectorized, you usually don't need to use an explicit loop. Here is a toy example with a binary A/B test analogous to your requirement:

v <- sample(c('A', 'B'), 100, replace = TRUE, prob = c(0.3, 0.7))
test <- v == 'B'
sum(test)
[1] 71

You would use "No Permanent Address" as your B test.

  • Related