如何在 ifelse 语句中忽略 NA [英] How to ignore NA in ifelse statement

查看:22
本文介绍了如何在 ifelse 语句中忽略 NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 SAS 来到 R,其中数字缺失设置为无穷大.所以我们只能说:

I came to R from SAS, where numeric missing is set to infinity. So we can just say:

positiveA = A > 0;

在 R 中,我必须像这样冗长:

In R, I have to be verbose like:

positiveA <- ifelse(is.na(A),0, ifelse(A > 0, 1, 0))

我发现这种语法很难阅读.无论如何我可以修改 ifelse 函数以将 NA 视为对于所有比较条件始终为假的特殊值?如果没有,将 NA 视为 -Inf 也可以.

I find this syntax is hard to read. Is there anyway I can modify ifelse function to consider NA a special value that is always false for all comparison conditions? If not, considering NA as -Inf will work too.

同样,在字符变量的 ifelse 语句中将 NA 设置为 ''(空白).

Similarly, setting NA to '' (blank) in ifelse statement for character variables.

谢谢.

推荐答案

这个语法更容易阅读:

x <- c(NA, 1, 0, -1)

(x > 0) & (!is.na(x)) 
# [1] FALSE  TRUE FALSE FALSE

(外圆括号不是必需的,但会使语句更容易被机器以外的几乎任何人阅读.)

(The outer parentheses aren't necessary, but will make the statement easier to read for almost anyone other than the machine.)

编辑:

## If you want 0s and 1s
((x > 0) & (!is.na(x))) * 1
# [1] 0 1 0 0

最后,你可以把整个东西变成一个函数:

Finally, you can make the whole thing into a function:

isPos <- function(x) {
    (x > 0) & (!is.na(x)) * 1
}

isPos(x)
# [1] 0 1 0 0

这篇关于如何在 ifelse 语句中忽略 NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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