gpt4 book ai didi

R 不能将 NaN 转换为 NA

转载 作者:行者123 更新时间:2023-12-04 09:04:25 25 4
gpt4 key购买 nike

我有一个包含多个因子列的数据框,其中包含 NaN是我想转换为 NA的(NaN 似乎是使用线性回归对象预测新数据的问题)。

> tester1 <- c("2", "2", "3", "4", "2", "3", NaN)
> tester1
[1] "2" "2" "3" "4" "2" "3" "NaN"
> tester1[is.nan(tester1)] = NA
> tester1
[1] "2" "2" "3" "4" "2" "3" "NaN"
> tester1[is.nan(tester1)] = "NA"
> tester1
[1] "2" "2" "3" "4" "2" "3" "NaN"

最佳答案

问题在于:您的向量在模式下是字符,所以它当然不是“数字”。最后一个元素被解释为字符串“NaN”。使用 is.nan只有当向量是数字时才有意义。如果您想在字符向量中丢失一个值(以便回归函数对其进行正确处理),请使用(不带任何引号),NA_character_ .

> tester1 <- c("2", "2", "3", "4", "2", "3", NA_character_)
> tester1
[1] "2" "2" "3" "4" "2" "3" NA
> is.na(tester1)
[1] FALSE FALSE FALSE FALSE FALSE FALSE TRUE

“NA”和“NaN”在字符向量中都没有真正缺失。如果由于某种原因,因子变量中的值是“NaN”,那么您就可以只使用逻辑索引:
tester1[tester1 == "NaN"] = "NA"  
# but that would not really be a missing value either
# and it might screw up a factor variable anyway.

tester1[tester1=="NaN"] <- "NA"
Warning message:
In `[<-.factor`(`*tmp*`, tester1 == "NaN", value = "NA") :
invalid factor level, NAs generated
##########
tester1 <- factor(c("2", "2", "3", "4", "2", "3", NaN))

> tester1[tester1 =="NaN"] <- NA_character_
> tester1
[1] 2 2 3 4 2 3 <NA>
Levels: 2 3 4 NaN

最后的结果可能令人惊讶。还有一个剩余的“NaN”级别,但没有一个元素是“NaN”。相反,“NaN”元素现在是一个真正的缺失值,在 print 中表示为 。

关于R 不能将 NaN 转换为 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9473103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com