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

为君一笑 提交于 2019-12-01 12:42:31

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")
}

You have a binary problem. There is no reason to use ifelse. Work with logical values:

bulbs <- rep(FALSE, 100)
for (i in 1:100) bulbs[!((1:100) %% i)] <- !bulbs[!((1:100) %% i)]
which(bulbs)
#[1]   1   4   9  16  25  36  49  64  81 100
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!