【问题标题】:Replace the NA values of a column variable for the mean of each one将列变量的 NA 值替换为每个变量的平均值
【发布时间】:2021-01-15 08:57:46
【问题描述】:

![1]:https://i.stack.imgur.com/CAA6g.png

所以我有以下数据框 (df),其中包含一些 NA 值的列。就我的项目而言,我真的不想拥有任何 NA 值。此外,我需要将所有这些 NA 值替换为每个列变量的平均值。

非常感谢

【问题讨论】:

标签: r dataframe mean na


【解决方案1】:

你可以试试

library(dplyr)
library(zoo)

df %>%
  na.aggregate()

这将用每列的平均值替换所有 NA 值

【讨论】:

  • 究竟是什么不工作?错误信息是什么?你在运行代码之前安装了库吗?
  • 实际上没有错误,但是当我创建一个 str(df) 来查看变量的一些值时,NA 仍然存在。
  • 您能否提供一个数据示例,例如dput() ?
【解决方案2】:
NA2mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
df<-replace(df, TRUE, lapply(df, NA2mean))

答案

【讨论】:

    猜你喜欢
    • 2013-08-06
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 2020-09-01
    • 2013-12-28
    • 1970-01-01
    相关资源
    最近更新 更多