这里的问题:你的载体是模式字符,所以当然这“不是一个数字”。最后一个元素被解释为字符串“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”都不是真的丢失。如果由于某种原因,有在为“南”,那么你就已经能够一个因素变量的值只使用逻辑索引:
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中表示为。
你可能想看看'setattr'从data.table包中查看MatthewDowle对我今天早些时候的问题的回答:http://stackoverflow.com/questions/9463980/how-to-assign-within-apply-family – 2012-02-27 22:24:17
这个例子没有任何意义:你如何建议使用charact呃线性回归数据? – 2012-02-27 23:00:38
这是一个因素。最后我检查了lm()可以处理w /因素。我应该在这个例子中抛出一个因素()。 – screechOwl 2012-02-27 23:12:14