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

前端 未结 2 588
孤城傲影
孤城傲影 2021-01-15 20:33

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

相关标签:
2条回答
  • 2021-01-15 21:27

    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")
    }
    
    0 讨论(0)
  • 2021-01-15 21:27

    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
    
    0 讨论(0)
提交回复
热议问题