首页 > 解决方案 > 使用预定权重的几列的加权平均值

问题描述

假设我有:

weights <- c(0.15, 0.25, 0.11, 0.9, 0.35, 0.05)

以及以下数据表Phones

make     model    price    users    rating    continent    market       years   success
Nokia     3310    800       5000       5       Europe     4000000        30        yes
Huawei    Foto    500      10000       7       Asia       1200000        10       no
Apple     XS      1500     90000       8       NAmerica   4200000         8        yes
Mi        125     300        500       5       Asia        300000         3        yes

我想添加一个名为 的新列Impact,它是权重乘以列price, users, rating, market, and years

到目前为止,我可以使用以下方法获取列的平均值:

Phones$wt <- rowMeans(subset(Phones, select = c(price, users, rating, market, years)), na.rm = TRUE)

所以,我想根据我手动选择的权重做一个加权平均值。

标签: r

解决方案


加权平均值与矩阵乘法相同,只是您另外将结果除以权重之和。你有 6 个权重和 5 列,所以我删除了最后一个权重。

m <- as.matrix(subset(Phones, select = c(price, users, rating, market, years)))

weights <- c(0.15, 0.25, 0.11, 0.9, 0.35)

m %*% weights / sum(weights)

#           [,1]
# [1,] 2046239.2
# [2,]  615101.9
# [3,] 2160641.3
# [4,]  153506.6

使用的数据:

Phones <- data.table::fread('
make     model    price    users    rating    continent    market       years   success
Nokia     3310    800       5000       5       Europe     4000000        30        yes
Huawei    Foto    500      10000       7       Asia       1200000        10       no
Apple     XS      1500     90000       8       NAmerica   4200000         8        yes
Mi        125     300        500       5       Asia        300000         3        yes
')

推荐阅读