且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用R中的分组均值替换NA?

更新时间:2023-02-18 11:28:47

我稍微修改了您的示例,因为您提供的数据框具有不同长度的列,但这应该可以解决您的问题:

I slightly changed your example, because the data frame you provided had columns of different lengths, but this should solve your problem:

首先,我将软件包加载到tidyverse中.然后我按月对数据分组.第二个管道运行mutate_all函数,因此它会自动更改所有列.

First, I loaded the packages in tidyverse. Then I grouped data by month. The second pipe runs a mutate_all function so it automatically changes all columns.

library(tidyverse)

df <- tibble(x1 = c(13, NA, 16, 17, 16, 12), x2 = c(1, 4, 3, 5, NA, 4),
             month = c(1, 1, 1, 2, 2, 2))


new_df <- df %>%  group_by(month) %>%
  mutate_all(funs(ifelse(is.na(.), mean(., na.rm = TRUE),.)))

让我知道这是否有帮助.

Let me know if this is of any help.