计算 NA、NAN 和 Inf 时的奇怪行为
Strange behavior while counting NAs, NANs and Inf's
我编写了一个小函数来计算 tibble 数据框中 NA、NaN 和 Inf 的数量,如下所示:
check.for.missing.values <- function(df) {
return( sum(is.na(as.matrix(df)) & !is.nan(as.matrix(df))) + #NAs
sum(is.infinite(as.matrix(df))) + #Infs
sum(is.nan(as.matrix(df))) #NaNs
)}
我用以下小标题测试了它:
x1 <- tibble(x = 1:7,
y = c(NA,NA,Inf,Inf,Inf,-Inf,-Inf),
z = c(-Inf,-Inf,NaN,NaN,NaN,NaN,NaN))
x1
# A tibble: 7 × 3
x y z
<int> <dbl> <dbl>
1 1 NA -Inf
2 2 NA -Inf
3 3 Inf NaN
4 4 Inf NaN
5 5 Inf NaN
6 6 -Inf NaN
7 7 -Inf NaN`
然后我得到
check.for.missing.values(x1)
[1] 14
这当然是正确答案。
现在,如果我传递给函数的小标题恰好包含日期格式的观察结果,那么函数就会停止工作,我不知道为什么:
x2 <- mutate(x1, date = as.Date('01/07/2008','%d/%m/%Y'))
x2
# A tibble: 7 × 4
x y z date
<int> <dbl> <dbl> <date>
1 1 NA -Inf 2008-07-01
2 2 NA -Inf 2008-07-01
3 3 Inf NaN 2008-07-01
4 4 Inf NaN 2008-07-01
5 5 Inf NaN 2008-07-01
6 6 -Inf NaN 2008-07-01
7 7 -Inf NaN 2008-07-01`
check.for.missing.values(x2)
[1] 7
关于发生了什么的任何线索?
谢谢
雷耶玛
正如@nicola 所提到的,您的问题在于您正在将数据框转换为矩阵。在这样做时,您强制每个 "cell" 强制转换为单个 class,在这种情况下最终成为 "character" class,而您的 Inf
和 -Inf
不再被你的函数捕获。
您可以通过 apply
遍历数据框中的列来完成您想做的事情,而无需求助于矩阵转换。在您的情况下,sapply
会起作用。
check.for.missing.values <- function(df) {
sum( sapply( df, function(x) {
sum( { is.na(x) & !is.nan(x) } |
is.infinite(x) |
is.nan(x) )
} ) )
}
sapply
遍历每一列,将匹配给定条件集的所有出现相加。 returns 一个数字向量,然后可以再次 sum
d 得到总数。
check.for.missing.values(x2)
[1] 14
我编写了一个小函数来计算 tibble 数据框中 NA、NaN 和 Inf 的数量,如下所示:
check.for.missing.values <- function(df) {
return( sum(is.na(as.matrix(df)) & !is.nan(as.matrix(df))) + #NAs
sum(is.infinite(as.matrix(df))) + #Infs
sum(is.nan(as.matrix(df))) #NaNs
)}
我用以下小标题测试了它:
x1 <- tibble(x = 1:7,
y = c(NA,NA,Inf,Inf,Inf,-Inf,-Inf),
z = c(-Inf,-Inf,NaN,NaN,NaN,NaN,NaN))
x1
# A tibble: 7 × 3
x y z
<int> <dbl> <dbl>
1 1 NA -Inf
2 2 NA -Inf
3 3 Inf NaN
4 4 Inf NaN
5 5 Inf NaN
6 6 -Inf NaN
7 7 -Inf NaN`
然后我得到
check.for.missing.values(x1)
[1] 14
这当然是正确答案。
现在,如果我传递给函数的小标题恰好包含日期格式的观察结果,那么函数就会停止工作,我不知道为什么:
x2 <- mutate(x1, date = as.Date('01/07/2008','%d/%m/%Y'))
x2
# A tibble: 7 × 4
x y z date
<int> <dbl> <dbl> <date>
1 1 NA -Inf 2008-07-01
2 2 NA -Inf 2008-07-01
3 3 Inf NaN 2008-07-01
4 4 Inf NaN 2008-07-01
5 5 Inf NaN 2008-07-01
6 6 -Inf NaN 2008-07-01
7 7 -Inf NaN 2008-07-01`
check.for.missing.values(x2)
[1] 7
关于发生了什么的任何线索?
谢谢
雷耶玛
正如@nicola 所提到的,您的问题在于您正在将数据框转换为矩阵。在这样做时,您强制每个 "cell" 强制转换为单个 class,在这种情况下最终成为 "character" class,而您的 Inf
和 -Inf
不再被你的函数捕获。
您可以通过 apply
遍历数据框中的列来完成您想做的事情,而无需求助于矩阵转换。在您的情况下,sapply
会起作用。
check.for.missing.values <- function(df) {
sum( sapply( df, function(x) {
sum( { is.na(x) & !is.nan(x) } |
is.infinite(x) |
is.nan(x) )
} ) )
}
sapply
遍历每一列,将匹配给定条件集的所有出现相加。 returns 一个数字向量,然后可以再次 sum
d 得到总数。
check.for.missing.values(x2)
[1] 14