gpt4 book ai didi

R ifelse - 向量顺序的意外变化

转载 作者:行者123 更新时间:2023-12-04 11:13:46 26 4
gpt4 key购买 nike

运行后我得到了意想不到的结果:

 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 8yes 的索引在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com