Minchul Shin Minchul Shin - 3 months ago 11
R Question

R: How to use ifelse statement for a vector of characters

I am trying to solve a quiz using R, but my code does not work properly. I tried debugging, but it seems that the ifelse statement fails to work at certain numbers that seem pretty random.

Here is the quiz: http://puzzles.nigelcoldwell.co.uk/six.htm

switches <- rep("off", 100)
for(i in 1:100){
k <- c(seq(i, 100, i))
ifelse(switches[k] == "off", switches[k] <- "on", switches[k] <- "off")
}


When I run this code, I get "on" for 14, 22, 26, 30, 34, etc in which I should have got "off." Is there a mistake in the way I applied ifelse statement to a vector with vectorized index?

Answer

The ifelse syntax should be

switches <- rep("off", 100)
for(i in 1:100){
  k <-  seq(i, 100, i)
  switches[k] <- ifelse(switches[k] == "off",  "on", "off")
}
Comments