根据其他两列创建新列,但在两列中观察时取平均值

Create new column based on two other columns, but average when observed in both

我有两个数字列 score.ascore.b。我想创建一个新变量 score.c 来从 a 或 b 转移观察到的分数,但是当它们在两者中都被观察到时,我需要取平均值。

help <- data.frame(deid = c(5, 7, 12, 15, 25, 32, 42, 77, 92, 100, 112, 113),
               score.a = c(NA, 2, 2, 2, NA, NA, NA, NA, NA, NA, 2, NA),
               score.b = c(4, NA, NA, 4, 4, 4, NA, NA, 4, 4, NA, 4))

创建

    deid score.a score.b
1     5      NA       4
2     7       2      NA
3    12       2      NA
4    15       2       4
5    25      NA       4
6    32      NA       4
7    42      NA      NA
8    77      NA      NA
9    92      NA       4
10  100      NA       4
11  112       2      NA
12  113      NA       4

我希望创建一个看起来像

的df
     deid score.a score.b score.c
1     5      NA       4     4
2     7       2      NA     2
3    12       2      NA     2
4    15       2       4     3
5    25      NA       4     4
6    32      NA       4     4
7    42      NA      NA     NA
8    77      NA      NA     NA
9    92      NA       4     4
10  100      NA       4     4
11  112       2      NA     2
12  113      NA       4     4

例如,第 4 行取平均值。

我的尝试使用了 help %>% group_by(deid) %>% mutate(score.c = (score.a + score.b)/2),但这只处理了两列中观察到的数据。

尝试

  help$score.c <- rowMeans(help[2:3], na.rm=TRUE)

或者 dplyr 的可能方法(未彻底测试)

 library(dplyr)
 help %>%
     mutate(val= (pmax(score.a, score.b, na.rm=TRUE)+
                  pmin(score.a, score.b, na.rm=TRUE))/2)

一个data.table解决方案是:

library(data.table)
setDT(help)
help[,.(rMean=rowMeans(.SD,na.rm = T)),.SDcols = c('score.a','score.b')]