且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在R中使用哪个函数的ifelse行为

更新时间:2023-12-01 14:13:34

你实际上不想用 ifelse 。正如BondedDust指出的那样,您应该将 ifelse 视为一个函数,该函数接受三个向量,并根据第一个中的TRUE / FALSE值从后两个中选择值。或者,正如文档所说:

You actually don't want to use ifelse in this case. As BondedDust pointed out, you should think of ifelse as a function that takes three vectors and picks values out of the second two based on the TRUE/FALSE values in the first. Or, as the documentation puts it:


ifelse返回一个与test相同形状的值,其中填充
并选择了元素来自是或否,取决于测试的
元素是TRUE还是FALSE。

ifelse returns a value with the same shape as test which is filled with elements selected from either yes or no depending on whether the element of test is TRUE or FALSE.

您可能只是想使用一个普通的 if 语句。

You probably simply wanted to use a regular if statement instead.

ifelse $ c $的一个潜在混淆c>是 回收参数。具体来说,如果我们这样做

One potential confusion with ifelse is that it does recycle arguments. Specifically, if we do

ifelse(rnorm(10) < 0,-1,1)

你会注意到第一个参数是长度为10的逻辑向量,但我们的第二个向量都是长度一。 R将根据需要简单地扩展它们以匹配第一个参数的长度。即使长度不能均匀扩展到正确的长度,也会发生这种情况。

you'll note that the first argument is a logical vector of length 10, but our second two "vectors" are both of length one. R will simply extend them as needed to match the length of the first argument. This will happen even if the lengths are not evenly extendable to the correct length.