当其中一个选项产生NA时,在R中使用ifelse? [英] Using ifelse in R when one of the options produces NAs?

查看:195
本文介绍了当其中一个选项产生NA时,在R中使用ifelse?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向量化一个依赖于检查条件的函数,并根据此条件是TRUE还是FALSE,分别返回两个函数之一的结果.问题在于,当条件为FALSE时,无法评估第一个函数.然后,ifelse返回正确的值,但也会产生警告.我想产生一个不会产生警告的函数.

I want to vectorize a function that relies on checking a condition and depending on whether this condition is TRUE or FALSE, return the outcome of one of two functions, respectively. The problem is that, when the condition is FALSE, the first function cannot be evaluated. Then, ifelse returns the correct values but it also produces a warning. I would like to produce a function that does not produce warnings.

我尝试了ifelse(),但是它不起作用.我期望当条件为FALSE时,此命令将跳过对第一个函数的求值.

I have tried ifelse(), but it does not work. I was expecting that this command would skip the evaluation of the first function when the condition is FALSE.

这是R代码的说明部分

p = c(-1,1,-1,1,-1,-1,-1,1)

ifelse(p>0, sqrt(p), p^2)

返回

[1] 1 1 1 1 1 1 1 1
Warning message:
In sqrt(p) : NaNs produced

如您所见,结果是正确的,但是由于某种原因,当条件为FALSE时,它将在第一个函数处对函数进行求值.因此,我想以某种方式避免这个问题.

As you can see, the outcome is correct but, for some reason, it evaluates the function at the first function when condition is FALSE. Thus, I would like to somehow avoid this issue.

推荐答案

我们可以创建一个numeric向量,然后根据'p'提出的条件填充元素.

We can create a numeric vector and then fill the elements based on the condition put forward by 'p'

out <- numeric(length(p))
out[p > 0] <- sqrt(p[p > 0])
out[p <= 0] <- p[p <= 0]^2


对于ifelse,我们需要具有相同length的所有参数.根据?ifelse


With ifelse we need to have all arguments of the same length. According to ?ifelse

ifelse(测试,是,否)

ifelse(test, yes, no)

具有相同长度和属性(包括尺寸和 "class")作为测试值和来自yes或no值的数据值

A vector of the same length and attributes (including dimensions and "class") as test and data values from the values of yes or no

发生的事情是我们对整个矢量都进行了计算,并根据test条件替换了'p'的值.对于sqrt,负值肯定会发出警告,并输出为NaN.虽然NaN元素未显示在输出中,但警告已被打印.该警告是一种友好的警告,但可以使用suppressWarnings

What happens is that we do both the calculations on the entire vector and replace the values of 'p' based on the test condition. For sqrt, the negative values definitely gives warning and output as NaN. While the NaN elements don't show up in the output, the warning was already printed. The warning is a friendly one, but can be suppressed with suppressWarnings

这篇关于当其中一个选项产生NA时,在R中使用ifelse?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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