[英]Weighting elements of a matrix based on a coefficient dataframe in R
I have got this coefficient table under the form of a dataframe
: 我已经以
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))
I would like to apply it to a matrix that has 7 dimensions that has the same variables as my coefficient dataframe
. 我想将其应用于具有7个维度的矩阵,该维度具有与我的系数
dataframe
相同的变量。 For now this is how it looks: 现在看起来是这样的:
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
I would like however to use my coefficient matrix to weight the elements of the matrix based on the formula I've used to create the coefficients, namely: min(BudgetRange1,BudgetRange2) / max(BudgetRange1,BudgetRange2) . 但是,我想使用系数矩阵根据我用来创建系数的公式对矩阵的元素进行加权,即:min(BudgetRange1,BudgetRange2)/ max(BudgetRange1,BudgetRange2)。
The first row has for example a budget of "1-5", the respective column should therefore take value 1. The other columns should take their respective value based on the same column "1-5" of the coefficient matrix (A). 例如,第一行的预算为“ 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
Anyone knows how? 有人知道吗? Thanks for reading so far
感谢到目前为止的阅读
Assuming the columns (ie 'less_than_1', '1-5', '5-20' ...) are exaclty in the same order for both coefficient_table
and A
, you can use matrix multiplication : 假设列(即“less_than_1”,“1-5”,“5-20” ......)的exaclty以相同的顺序两个
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.