在数据框列中将NA替换为0 [英] Replace NA with 0 in a data frame column
本文介绍了在数据框列中将NA替换为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
在NA中将NA设置为0
我有一个带列的data.frame具有 NA
值。我想将 NA
替换为 0
或任何其他值。我尝试了很多线程和方法,但没有得到结果。我尝试了以下方法。
I have a data.frame with a column having NA
values. I want to replace NA
with 0
or any other value. I have tried a lot of threads and methods but it did not give me the result. I have tried the below methods.
a$x[a$x == NA] <- 0;
a[ , c("x")] <- apply(a[ , c("x")], 1, function(z){replace(z, is.na(z), 0)});
a$x[is.na(a$x), ] <- 0;
以上方法均未将 NA
替换为<列中的0 code> x 表示数据。帧 a
。为什么?
None of the above methods replaced NA
with 0 in column x
for data.frame a
. Why?
推荐答案
到目前为止,没有人适合指出为什么不起作用:
Since nobody so far felt fit to point out why what you're trying doesn't work:
-
NA == NA
不返回TRUE
,它返回NA
(因为与未定义的值进行比较应产生未定义的结果)。 - 您尝试在原子矢量上调用
apply
。您不能使用apply
遍历列中的元素。 - 您的下标不可用-您正在尝试为
a $ x
提供两个索引,该索引只是该列(原子向量)。
NA == NA
doesn't returnTRUE
, it returnsNA
(since comparing to undefined values should yield an undefined result).- You're trying to call
apply
on an atomic vector. You can't useapply
to loop over the elements in a column. - Your subscripts are off - you're trying to give two indices into
a$x
, which is just the column (an atomic vector).
我将修正3.以得到 a $ x [is.na( a $ x)]<-0
这篇关于在数据框列中将NA替换为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文