Search code examples
rif-statementfor-loopany

using if(any()) in a for loop


I would like to generate a loop as such:

group1 = c(1,3,7,25)

for (ii in 1:25){
    if (ii == any(group1)){test = 5} else {test=1}
}

I am receiving a warning about coercing my argument of type 'double' to logical. The result is that only my else statement is being used. What does that mean and how do I fix this? Thank you.


Solution

  • It's not exactly clear what you do want. Possibly

     test <- c(1,5)[1+(1:25) %in% group1]
    

    Same result as:

    test <- ifelse( 1:25 %in% group1, 5, 1)
    

    Oh, OK, i'll make the for-loopy version, too:

    test <- integer(25)
    for (ii in 1:25){
       if (ii %in% group1){test[ii] <- 5} else {test[ii] <- 1}
                    }
    test