使用数据表的同一列的平均值替换NAs [英] Replace NAs with mean of the same column of a data.table

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

问题描述

我想用同一列的平均值替换DATA TABLE列中的NA。我做了以下。但它不工作。

  ww<  -  data.table(iris)

ww< ; - ww [1:5,]

ww [1,1] < - NA

Sepal.Length Sepal.Width Petal.Length Petal.Width种类
1:NA 3.5 1.4 0.2 setosa
2:4.9 3.0 1.4 0.2 setosa
3:4.7 3.2 1.3 0.2 setosa
4:4.6 3.1 1.5 0.2 setosa
5:5.0 3.6 1.4 0.2 setosa


ww [is.na(Sepal.Length),Sepal.Length:= mean(Sepal.Length,na.rm = T)]

Sepal.Length Sepal.Width Petal.Length Petal.Width种类
1:NaN 3.5 1.4 0.2 setosa
2:4.9 3.0 1.4 0.2 setosa
3:4.7 3.2 1.3 0.2 setosa
4:4.6 3.1 1.5 0.2 setosa
5:5.0 3.6 1.4 0.2 setosa

(4.9,4.7,4.6,5.0)的平均值?



什么是替代



我想要数据表的语法。

na.aggregate 将NAs替换为同一列中非NA的平均值:

  library(zoo)

ww [,Sepal.Length:= na.aggregate(Sepal.Length)]


I want to replace NAs present in a column of a DATA TABLE with the mean of the same column. I am doing the following. But it is not working.

ww <- data.table(iris)

ww <- ww[1:5 , ]

ww[1,1] <- NA

   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1:           NA         3.5          1.4         0.2  setosa
2:          4.9         3.0          1.4         0.2  setosa
3:          4.7         3.2          1.3         0.2  setosa
4:          4.6         3.1          1.5         0.2  setosa
5:          5.0         3.6          1.4         0.2  setosa


ww[is.na(Sepal.Length) , Sepal.Length:= mean(Sepal.Length, na.rm = T)]

   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1:          NaN         3.5          1.4         0.2  setosa
2:          4.9         3.0          1.4         0.2  setosa
3:          4.7         3.2          1.3         0.2  setosa
4:          4.6         3.1          1.5         0.2  setosa
5:          5.0         3.6          1.4         0.2  setosa

Why am I getting NaN in place of NA when it should have been the mean of the rest of the values (4.9, 4.7, 4.6, 5.0)?

What is the alternate of acheiving this in case something is wrong with this syntax?

I want to the syntax for the data table.

解决方案

na.aggregate in the zoo package replaces NAs with the mean of the non-NAs in the same column:

library(zoo)

ww[, Sepal.Length := na.aggregate(Sepal.Length)]

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

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