首页 > 解决方案 > 基于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

有谁知道怎么做?感谢您到目前为止的阅读

标签: rdataframe

解决方案


假设列(即 '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)

推荐阅读