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

喜欢而已 提交于 2019-12-01 09:59:45

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/39242872/r-how-to-use-ifelse-statement-for-a-vector-of-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!