r - 基于R中的系数数据框的矩阵的加权元素
问题描述
我有以下形式的系数表dataframe
:
coefficient_table <- data.frame("less_than_1" = c( 1, 0.5, 0.1, 0.025, 0.010, 0.005, 0.001),
"1-5" = c(0.500, 1.000, 0.200, 0.050, 0.020, 0.010, 0.002),
"5-20" = c(0.10, 0.20, 1.00, 0.25, 0.10, 0.05, 0.01),
"20-50" = c(0.025, 0.050, 0.250, 1.000, 0.400, 0.200, 0.040),
"50-100" = c(0.010, 0.020, 0.10, 0.400, 1.00, 0.500, 0.100),
"100-500" = c(0.005, 0.010, 0.050, 0.200, 0.500, 1.000, 0.200),
"more_than_500" = c(0.001, 0.002, 0.010, 0.040, 0.100, 0.200, 1.000))
我想将其应用于具有 7 个维度的矩阵,该矩阵具有与我的系数相同的变量dataframe
。现在看起来是这样的:
A <- data.frame("less_than_1" = c(0,0,1,0), "1-5" = c(1,0,0,0), "5-20" = c(0,0,0,0),
"20-50" = c(0,1,0,1), "50-100" = c(0,0,0,0), "100-500" = c(0,0,0,0),
"more_than_500" = c(0,0,0,0))
A <- as.matrix(A)
less_than_1 1-5 5-20 20-50 50-100 100-500 more_than_500
1 0 1 0 0 0 0 0
2 0 0 0 1 0 0 0
3 1 0 0 0 0 0 0
4 0 0 0 1 0 0 0
但是,我想使用我的系数矩阵根据我用来创建系数的公式来加权矩阵的元素,即: min(BudgetRange1,BudgetRange2) / max(BudgetRange1,BudgetRange2) 。
例如,第一行的预算为“1-5”,因此相应的列应取值 1。其他列应基于系数矩阵 (A) 的同一列“1-5”取其各自的值。
table_z
less_than_1 1-5 5-20 20-50 50-100 100-500 more_than_500
1 0.5 1 0.2 0.05 0.02 0.01 0.002
2 0.025 0.05 0.25 1 0.4 0.2 0.04
3 1 0.5 0.1 0.025 0.01 0.005 0.001
4 0.025 0.05 0.25 1 0.4 0.2 0.04
有谁知道怎么做?感谢您到目前为止的阅读
解决方案
假设列(即 'less_than_1'、'1-5'、'5-20' ...)对于coefficient_table
和的顺序相同A
,则可以使用矩阵乘法:
Z <- as.matrix(A)%*%as.matrix(coefficient_table)
> Z
less_than_1 1-5 5-20 20-50 50-100 100-500 more_than_500
[1,] 0.500 1.00 0.20 0.050 0.02 0.010 0.002
[2,] 0.025 0.05 0.25 1.000 0.40 0.200 0.040
[3,] 1.000 0.50 0.10 0.025 0.01 0.005 0.001
[4,] 0.025 0.05 0.25 1.000 0.40 0.200 0.040
# where Z is a matrix, you can convert to data.frame if you need it :
table_z <- as.data.frame(Z)
推荐阅读
- python - 为通过整个文件夹循环运行 python 脚本创建一个 BAT 文件
- android - Android Studio - 没有 Android 核心库的源代码/javadocs
- python - 从 one-hot 表示到标签
- intellij-idea - 如何确定我使用 JavaFX 编写的游戏是否使用了足够的系统资源?
- unit-testing - Xamarin.Forms - 对使用 Autofac 中的 ServiceLocator 的方法进行单元测试
- javascript - VB.NET TCP 客户端与 NODE-RED TCP 侦听器进行双向通信
- java - 用于下载 jar 文件的 Maven 依赖项
- c# - 错误 CS1503:参数 1:无法从“字符串”转换为“System.IFormatProvider”
- r - 将任意数量的向量转换为数据帧,同时保留数据类型并将向量名称用作 R 中的列名
- html - 基本下拉菜单