[英]create a coefficient matrix based on a formula using elements of a data frame in R
I have the following dataframe
named (A) in R: 我在R中有以下名为(A)的
dataframe
:
A <- data.frame("budget_range" = c("less_than_1", "1-5", "5-20", "20-50", "50-100", "100-500", "more_than_500"),
"coefficient" = c(0.005, 0.01, 0.05, 0.2, 0.5, 1, 5))
Budget_range Coefficient
1_less_than_1 0.005
2_1-5 0.01
3_5-20 0.05
4_20-50 0.2
5_50-100 0.5
6_100-500 1
7_more_than_500 5
I now would like to create a 7x7 matrix where each element of the matrix = min(BudgetRange1,BudgetRange2) / max(BudgetRange1,BudgetRange2). 我现在想创建一个7x7矩阵,其中矩阵的每个元素= min(BudgetRange1,BudgetRange2)/ max(BudgetRange1,BudgetRange2)。
For example with element 2,1 or 1,2 (they should be the same), the math would be 0.005/0.01 = 0.5. 例如,对于元素2,1或1,2(它们应该相同),数学将为0.005 / 0.01 = 0.5。
It should give something like this: 它应该给出这样的内容:
1 2 3 4 5 6 7
1 1 0.5 0.1 0.025 0.01 0.005 0.001
2 0.5 1 0.2 0.05 0.02 0.01 0.002
3 ...
4
5
6
7
Any idea how to do it? 知道怎么做吗? Thanks a lot in advance!
在此先多谢!
We can use outer
to do this 我们可以使用
outer
来做到这一点
outer(A$coefficient, A$coefficient, FUN = function(...) pmin(...)/pmax(...))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#[1,] 1.000 0.500 0.10 0.025 0.01 0.005 0.001
#[2,] 0.500 1.000 0.20 0.050 0.02 0.010 0.002
#[3,] 0.100 0.200 1.00 0.250 0.10 0.050 0.010
#[4,] 0.025 0.050 0.25 1.000 0.40 0.200 0.040
#[5,] 0.010 0.020 0.10 0.400 1.00 0.500 0.100
#[6,] 0.005 0.010 0.05 0.200 0.50 1.000 0.200
#[7,] 0.001 0.002 0.01 0.040 0.10 0.200 1.000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.