首页 > 解决方案 > 用按时间和治疗分组的变量的平均值替换 NA

问题描述

我有一个数据框,类似于下面的数据框(请参阅 dput),记录变量随时间对治疗的响应:

df <- structure(list( time = c(0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 33, 33, 33, 33, 33, 33, 90, 90, 90, 90, 90, 90),
                      trt = structure(c(2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L),
                      .Label = c("1", "2"), class = "factor"), 
               A1 = c(6.301, 5.426, 5.6021, NA, NA, NA, 6.1663, 6.426, 6.8239, 2.301, 4.7047, 2.301, 5.8062, 4.97, 4.97, 2.301, 2.301, 2.301, 2.301, 2.301, 2.301, 2.301, 2.301, 2.301),
               B1 = c(5.727, 5.727, 5.4472, NA, NA, NA, 6.6021, 7.028, 7.1249, 3.028, 3.1663, 3.6021, 5.727, 5.2711, 5.2389, 3.3554, 3.9031, 4.2389, 3.727, 3.6021, 3.6021, 3.8239, 3.727, 3.426)),
               row.names = c(NA, -24L), class = c("tbl_df", "tbl", "data.frame"))

看起来是这样的:

    time trt      A1    B1
   <dbl> <fct> <dbl> <dbl>
 1     0 2      6.30  5.73
 2     0 2      5.43  5.73
 3     0 2      5.60  5.45
 4     0 1     NA    NA   
 5     0 1     NA    NA   
 6     0 1     NA    NA   
 7    14 2      6.17  6.60
 8    14 2      6.43  7.03
 9    14 2      6.82  7.12
10    14 1      2.30  3.03

在我们的实验中,我们并不总是在时间 == 0 时记录所有处理的值。我想在(且仅当)时间 == 0 时用 trt '2' 组的平均值替换任何缺失值 (NA)在时间 == 0。所以 A1 中的 NA 都变为 5.78,而 B1 中的 NA 变为 5.63。

使用herehere以及其他一些答案,我已经能够提出以下建议:

df %>% 
  mutate_if(is.numeric, funs(if_else(is.na(.),if_else(time == 0, 0, .), .)))

这会将时间 == 0 时的 NA 替换为 0(这对于我的一些变量很有用,其中在时间 == 0 的任何处理中都没有数据,但不是我在这里所追求的)。我也试过这个:

df %>% 
  mutate_if(is.numeric, funs(if_else(is.na(.),if_else(time == 0, mean(., na.rm = TRUE), .), .)))

这更接近我想要的,但是是对整个列/变量的值进行平均。当时间 == 0 时,我可以让它只平均来自治疗“2”的那些值吗?

标签: rdplyrna

解决方案


我想我会为此使用基础 R 中的索引:

within(df, {A1[is.na(A1) & time == 0] <- mean(A1[trt == "2" & time == 0])
            B1[is.na(B1) & time == 0] <- mean(B1[trt == "2" & time == 0])})
#> # A tibble: 24 x 4
#>     time trt      A1    B1
#>    <dbl> <fct> <dbl> <dbl>
#>  1     0 2      6.30  5.73
#>  2     0 2      5.43  5.73
#>  3     0 2      5.60  5.45
#>  4     0 1      5.78  5.63
#>  5     0 1      5.78  5.63
#>  6     0 1      5.78  5.63
#>  7    14 2      6.17  6.60
#>  8    14 2      6.43  7.03
#>  9    14 2      6.82  7.12
#> 10    14 1      2.30  3.03
#> # ... with 14 more rows

reprex 包于 2020-05-15 创建(v0.3.0)


推荐阅读