R 中的向量化 IF 语句?
x <- seq(0.1,10,0.1)
y <- if (x < 5) 1 else 2
这会发出警告(或自 R 版本 4.2.0 以来的错误),条件的长度 > 1..
我希望 if 能够对每种情况进行操作,而不是对整个向量进行操作。 我必须改变什么?
x <- seq(0.1,10,0.1)
y <- if (x < 5) 1 else 2
This gives a warning (or error since R version 4.2.0) that the condition has length > 1
.
I would want the if
to operate on every single case instead of operating on the whole vector.
What do I have to change?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
为了完整性:在大向量中,您可以使用索引来加快速度(我们经常在模拟中这样做,其中函数通常运行 1000 到 10000 次)。但只要没有必要,就使用
ifelse
。这样读起来容易多了。For completeness: In big vectors, you can use the indices to speed things up (we do that often in simulations, where functions typically run 1000 to 10000 times). But as long as it isn't necessary, just use
ifelse
. This reads a lot easier.y <- if (x < 5) 1 else 2
不对整个向量进行操作(您收到的警告告诉您仅使用条件的第一个元素)。您需要ifelse
:ifelse
对整个逻辑向量逐个元素进行操作。if
仅接受一个 逻辑值。请参阅?"if"
和?ifelse
y <- if (x < 5) 1 else 2
does not operate on the whole vector (the warning you receive tells you only the first element of the condition will be used). You wantifelse
:ifelse
operates on the whole logical vector, element-by-element.if
only accepts one logical value. See?"if"
and?ifelse
您也可以只创建一个逻辑向量并为其添加 1
如果想比较性能,这将是最快的解决方案
You could also just create a logical vector and 1 to it
If would like to compare performance, it would be the fastest solution
按照上面的帖子,您甚至可以使用和修改满足条件的向量元素。在我看来,如果计算速度更快不是成本更高,那么人们就应该这样做。
上一篇文章的代码最能回答这个问题。但如果我必须使用上面的代码我会这样做:
Following the above post you can even use and modify the elements of a vector satisfying the criteria. In my opinion if it's not more costly to compute faster one should always do it.
The code of the previous post is best to answer the question. But if I had to use the code above I would do: