用列均值替换缺失值 [英] Replace missing values with column mean

查看:73
本文介绍了用列均值替换缺失值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定如何遍历每列以将NA值替换为列均值.当我尝试使用以下内容替换一列时,效果很好.

I am not sure how to loop over each column to replace the NA values with the column mean. When I am trying to replace for one column using the following, it works well.

Column1[is.na(Column1)] <- round(mean(Column1, na.rm = TRUE))

循环列的代码不起作用:

The code for looping over columns is not working:

for(i in 1:ncol(data)){
    data[i][is.na(data[i])] <- round(mean(data[i], na.rm = TRUE))
}

这些值不会被替换.有人可以帮我吗?

the values are not replaced. Can someone please help me with this?

推荐答案

对代码进行相对简单的修改即可解决该问题:

A relatively simple modification of your code should solve the issue:

for(i in 1:ncol(data)){
  data[is.na(data[,i]), i] <- mean(data[,i], na.rm = TRUE)
}

这篇关于用列均值替换缺失值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆