处理 TRUE、FALSE、NA 和 NaN [英] Dealing with TRUE, FALSE, NA and NaN
问题描述
这是一个向量
a <- c(TRUE, FALSE, FALSE, NA, FALSE, TRUE, NA, FALSE, TRUE)
我想要一个简单的函数,每次a"中有 TRUE
时返回 TRUE
,每次有 a 时返回 FALSE
FALSE
或 "a" 中的 NA
.
I'd like a simple function that returns TRUE
everytime there is a TRUE
in "a", and FALSE
everytime there is a FALSE
or a NA
in "a".
以下三件事不起作用
a == TRUE
identical(TRUE, a)
isTRUE(a)
这是一个解决方案
a[-which(is.na(a))]
但这似乎不是一个简单明了的解决方案
but it doesn't seem to be a straightforward and easy solution
还有其他解决方案吗?
以下是我知道的一些函数(和运算符):
Here are some functions (and operators) I know:
identical()
isTRUE()
is.na()
na.rm()
&
|
!
还有哪些其他功能(运算符、提示等...)对处理
TRUE
、FALSE
、NA
、NaN
有用吗?NA
和NaN
有什么区别?除了
TRUE
、FALSE
、NA
和NaN
之外,还有其他逻辑事物"吗?Are there other "logical things" than
TRUE
,FALSE
,NA
andNaN
?非常感谢!
推荐答案
按顺序回答你的问题:
1)
==
运算符确实不会像您期望的那样处理 NA.一个非常有用的函数是来自 r-cookbook.com<的compareNA
函数/a>:1) The
==
operator does indeed not treat NA's as you would expect it to. A very useful function is thiscompareNA
function from r-cookbook.com:compareNA <- function(v1,v2) { # This function returns TRUE wherever elements are the same, including NA's, # and false everywhere else. same <- (v1 == v2) | (is.na(v1) & is.na(v2)) same[is.na(same)] <- FALSE return(same) }
2) NA 代表不可用",与一般的 NaN(非数字")不同.NA 一般用于一个数字的默认值,以代替缺失数据;NaN 通常是由于数字问题(取 -1 或类似的日志)而生成的.
2) NA stands for "Not available", and is not the same as the general NaN ("not a number"). NA is generally used for a default value for a number to stand in for missing data; NaN's are normally generated because a numerical issue (taking log of -1 or similar).
3) 我不太确定您所说的逻辑事物"是什么意思——许多不同的数据类型,包括数字向量,都可以用作逻辑运算符的输入.您可能想尝试阅读 R 逻辑运算符页面:http://stat.ethz.ch/R-manual/R-patched/library/base/html/Logic.html.
3) I'm not really sure what you mean by "logical things"--many different data types, including numeric vectors, can be used as input to logical operators. You might want to try reading the R logical operators page: http://stat.ethz.ch/R-manual/R-patched/library/base/html/Logic.html.
希望这会有所帮助!
这篇关于处理 TRUE、FALSE、NA 和 NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!