用 NA 计算几列的加权平均值

calculate weighted average over several columns with NA

我有这样一个数据框:

ID  duration1   duration2   total_duration  quantity1   quantity2
 1     5            2             7             3         1
 2     NA           4             4             3         4
 3     5            NA            5             2         NA

我想像这样对每个主题进行加权平均:

df$weighted_mean<-  ((df$duration1*df$quantity1) + (df$duration2*df$quantity2) ) / (df$total_duration)

但是因为我有 NA,所以这个命令不起作用而且不是很好....

结果是这样的:

ID  duration1   duration2   total_duration  quantity1   quantity2   weighted_mean
 1     5            2             7             3         1          2.43
 2     NA           4             4             3         4          4
 3     5            NA            5             2         NA         2

在此先感谢您的帮助

您可以利用 sumprodna.rm= 参数。

transform(df, z=sum(prod(duration1, quantity1, na.rm=T), na.rm=T) + 
       sum(prod(duration2, quantity2, na.rm=T), na.rm=T)/
       na.omit(total_duration))
#   ID duration1 duration2 total_duration quantity1 quantity2        z
# 1  1         5         2              7         3         1 454.5714
# 2  2        NA         4              4         3         4 458.0000
# 3  3         5        NA              5         2        NA 456.4000