在R中使用哪个函数的ifelse行为 [英] ifelse behaviour with which function in R

查看:104
本文介绍了在R中使用哪个函数的ifelse行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




刚刚玩了一些基本函数,如果我在ifelse条件为真时使用which()函数作为参数之一,ifelse的行为似乎很奇怪,例如:




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

如何制作ifelse使用哪个()函数返回正确的值?

似乎它只输出匹配条件的第一个值。为什么这样做?

我很感激你的回答。谢谢。

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.

推荐答案

你实际上不想用<在这种情况下code> 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 回收参数。具体来说,如果我们这样做

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.

这篇关于在R中使用哪个函数的ifelse行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆