从数据帧R中的0替换NA值 [英] Replace NA values from a column with 0 in data frame R
本文介绍了从数据帧R中的0替换NA值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
在R中设置NA为0
Possible Duplicate:
Set NA to 0 in R
我有具有 NA
值的列的data.frame。我想用 0
或任何其他值替换 NA
。我尝试了很多线程和方法,但没有给我结果。我尝试了以下方法。
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
在 x
的列中为0,表示data.frame 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
这篇关于从数据帧R中的0替换NA值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文