简体   繁体   English

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

[英]ifelse behaviour with which function in R

Just been playing with some basic functions and it seems rather strange how ifelse behaves if I use which() function as one of the arguments when the ifelse condition is true, eg:刚刚玩了一些基本函数,如果我使用 which() 函数作为 ifelse 条件为真时的参数之一,那么 ifelse 的行为似乎很奇怪,例如:

#I want to identify the location of all values above 6.5 
#only if there are more than 90 values in the vector a:

set.seed(100)
a <- rnorm(100, mean=5, sd=1)
ifelse(length(a)>90, which(a>6.5), NA)

I get this output:我得到这个输出:

[1] 4

When in fact it should be the following:实际上它应该是以下内容:

[1]  4 15 25 40 44 47 65

How then can I make ifelse return the correct values using which() function?那么如何让 ifelse 使用which()函数返回正确的值?
It seems it only outputs the first value that matches the condition.它似乎只输出与条件匹配的第一个值。 Why does it do that?为什么这样做?

You actually don't want to use ifelse in this case.在这种情况下,您实际上不想使用ifelse 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.正如 BondedDust 指出的那样,您应该将ifelse视为一个函数,它采用三个向量并根据第一个中的 TRUE/FALSE 值从后两个向量中挑选值。 Or, as the documentation puts it:或者,正如文档所说:

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. ifelse 返回一个与 test 具有相同形状的值,其中填充了从 yes 或 no 中选择的元素,具体取决于 test 的元素是 TRUE 还是 FALSE。

You probably simply wanted to use a regular if statement instead.您可能只是想改用常规的if语句。

One potential confusion with ifelse is that it does recycle arguments.ifelse一个潜在混淆是它确实回收了参数。 Specifically, if we do具体来说,如果我们这样做

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

you'll note that the first argument is a logical vector of length 10, but our second two "vectors" are both of length one.您会注意到第一个参数是长度为 10 的逻辑向量,但我们的第二个“向量”的长度均为 1。 R will simply extend them as needed to match the length of the first argument. R 将根据需要简单地扩展它们以匹配第一个参数的长度。 This will happen even if the lengths are not evenly extendable to the correct length.即使长度不能均匀地扩展到正确的长度,也会发生这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM