Question

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.

Was it helpful?

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

OTHER TIPS

You are using wrong any function

any(iterable) 

Return True if any element of the iterable is true. If the iterable is empty, return False.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top