在非指定列数中用组均值替换 NA

replace NA with groups mean in a non specified number of columns

我想用多列中每个组 collembolamite 的平均值替换 NA。这是一个包含 3 列的示例,但是我想应用这个包含 5000 列的数据框

dat <- read.table(text = 
                  "id    ID        length  width    extra
                  101   collembola  2.1     0.9     1
                  102   mite        NA      0.7     NA
                  103   mite        1.1     0.8     2
                  104   collembola  1       NA      3
                  105   collembola  1.5     0.5     4
                  106   mite        NA      NA      NA
                  106   mite        1.9     NA      4", 
                  header=TRUE)

如果我输入每一列就可以了

library(plyr)
impute.mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
data2 <- ddply(dat, ~ ID, transform, length = impute.mean(length))

我想应用计算每个单组 ID collembolamite 跨多个列的平均值的函数,下面是我尝试过的(它不起作用) :

dat2 <- ddply(dat, ~ ID, transform,  impute.mean(dat[,3:ncol(dat)]))

如果您不介意使用 dplyr:


library(dplyr)

dat %>% 
  group_by(ID) %>% 
  mutate_if(is.numeric, function(x) ifelse(is.na(x), mean(x, na.rm = TRUE), x))
#> # A tibble: 7 x 5
#> # Groups:   ID [2]
#>      id         ID length width extra
#>   <int>     <fctr>  <dbl> <dbl> <dbl>
#> 1   101 collembola    2.1  0.90     1
#> 2   102       mite    1.5  0.70     3
#> 3   103       mite    1.1  0.80     2
#> 4   104 collembola    1.0  0.70     3
#> 5   105 collembola    1.5  0.50     4
#> 6   106       mite    1.5  0.75     3
#> 7   106       mite    1.9  0.75     4

尝试

library(plyr)
impute.mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
dat2 <- ddply(dat, ~ ID, transform, length = impute.mean(length),
          width = impute.mean(width), extra = impute.mean(extra))