在尝试理解R中while()
命令背后的语法时,我遇到了引入两个条件的问题。有一个post on the topic,但它似乎不起作用。
玩具代码不言自明,非常简单:
> x = sample(c("Y", "M", "_"))
> y = sample(c("O", "U","E", "S", "H"))
>
> while(paste(x, collapse ="") != "MY_") x = sample(x)
> paste(x, collapse = "")
[1] "MY_"
>
> while(paste(y, collapse ="") != "HOUSE") y = sample(y)
> paste(y, collapse = "")
[1] "HOUSE"
>
> while(paste(x, collapse ="") != "MY_" && paste(y, collapse ="") != "HOUSE") x = sample(x); y = sample(y)
> paste(c(x, y), collapse = "")
[1] "MY_OEHSU"
错误的答案!预期答案是“MY_HOUSE”。
为什么&&
没有做到这一点?
感谢下面的评论!如果有正式答案,我将删除此编辑以信用到期。否则,如果它对其他人有帮助,这是正确的代码:
> x = sample(c("Y", "M", "_"))
> y = sample(c("O", "U","E", "S", "H"))
>
> while(paste(x, collapse ="") != "MY_") x = sample(x)
> paste(x, collapse = "")
[1] "MY_"
>
> while(paste(y, collapse ="") != "HOUSE") y = sample(y)
> paste(y, collapse = "")
[1] "HOUSE"
>
> while(paste(x, collapse ="") != "MY_" || paste(y, collapse ="") != "HOUSE") {x = sample(x); y = sample(y)}
> paste(c(x, y), collapse = "")
[1] "MY_HOUSE"