r - 使用预定权重的几列的加权平均值
问题描述
假设我有:
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)
所以,我想根据我手动选择的权重做一个加权平均值。
解决方案
加权平均值与矩阵乘法相同,只是您另外将结果除以权重之和。你有 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
')
推荐阅读
- .htaccess - htaccess - 子目录上的域重定向 - 缺少子目录名称
- python-3.x - 如何测试一种方法,其唯一目的是计算其睡眠持续时间并使其睡眠
- python - pynput 键盘记录器不写入文件
- html - 使用 CSS 将鼠标悬停在父元素上时更改子元素状态
- mysql - 如何加入到结果有时会以 - 符号开头的表?
- corda - 有没有办法以编程方式为多个 Corda 测试网节点请求一次性密钥?
- amazon-cloudformation - 您可以通过 Cloud Formation 在 AWS ECR 存储库上创建标签吗?
- javascript - 自定义字体 React-Native,[未处理的承诺拒绝:ReferenceError:找不到变量:ExpoFontLoader]
- javascript - 在浏览器中呈现时,为 Nuxt 应用程序创建自定义 Markdown-it 插件会导致 TypeError
- angular - routerLink 将组件实例的数据作为状态传递