ifelse behaviour with which function in R

不想你离开。 提交于 2019-12-25 00:36:43

问题




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, e.g.:

#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?
It seems it only outputs the first value that matches the condition. Why does it do that?
I would appreciate your answers.Thanks.


回答1:


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 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.

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

One potential confusion with ifelse is that it does recycle arguments. 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. 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.



来源:https://stackoverflow.com/questions/26183904/ifelse-behaviour-with-which-function-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!