运行后我得到了意想不到的结果:
test = c(rep(FALSE, 2), rep(TRUE, 6))
ifelse(test, c(1:8)[test], 1)
[1] 1 1 5 6 7 8 3 4
我本以为 1 1 3 4 5 6 7 8
但 yes
的索引在 ifelse(test, yes, no)
被转动。也许我需要更多咖啡,但如果有人能解释这个结果背后的逻辑,我将不胜感激。
最佳答案
ifelse
中向量的长度应该相同。在 OP 的代码中,第二个参数再次被子集化,而第三个参数 1 被回收(虽然很好)
ifelse(test, 1:8, 1)
#[1] 1 1 3 4 5 6 7 8
在?ifelse
的文档中有说明
If yes or no are too short, their elements are recycled. yes will be evaluated if and only if any element of test is true, and analogously for no.
这里,'yes', 'no' 表示 ifelse
中的一般用法参数
ifelse(test, yes, no)
关于R ifelse - 向量顺序的意外变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44699799/