R中数据表中的查找值

时间:2018-08-25 21:08:29

标签: r lookup

所以我希望能够基于df表找到ScoreLU值。例如,DSCRpd中的1.3730682的值应返回60的ScoreLU值,即最接近的值。是的,就像excel中的vlookup函数一样。是否有r软件包可以帮助您,或者有人可以通过其他方式解决此问题。

我有2个数据表,第一个数据表称为df

[df][1]
   DSCRpd Leverage         TCB
1  1.3730682 2.010122 -1590099.11
2  1.0449597 2.680051   493370.85
3  1.0311141 4.790531    21594.63
4  1.3923007 3.279903  -499326.76
5  1.6443938 3.853003   988780.79
6  0.6265976 1.814359  1003736.73
7  2.1025253 4.412528  1245305.83
8  1.2872873 2.074424  -688305.83
9  0.5088294 2.504510  1406986.68
10 1.7794307 3.724905  1132513.33

第二个表中的查找值存储为:

[ScoreLU][2]
   ScoreLU DSCRpd Leverage     TCB
 1:       0   0.65      5.0       0
 2:      10   0.80      4.5  100000
 3:      20   0.95      4.0  250000
 4:      30   1.10      3.5  500000
 5:      40   1.20      3.0  850000
 6:      50   1.26      2.5 1250000
 7:      60   1.35      2.0 1700000
 8:      70   1.65      1.5 2300000
 9:      80   2.00      1.0 2900000
10:      90   2.30      0.5 3600000

1 个答案:

答案 0 :(得分:0)

使用data.table

setDT(df1)[, ScoreLU  := setDT(df2)[df1, ScoreLU , on = "DSCRpd", roll = "nearest"]]

       DSCRpd Leverage         TCB ScoreLU
 1: 1.3730682 2.010122 -1590099.11      60
 2: 1.0449597 2.680051   493370.85      30
 3: 1.0311141 4.790531    21594.63      30
 4: 1.3923007 3.279903  -499326.76      60
 5: 1.6443938 3.853003   988780.79      70
 6: 0.6265976 1.814359  1003736.73       0
 7: 2.1025253 4.412528  1245305.83      80
 8: 1.2872873 2.074424  -688305.83      50
 9: 0.5088294 2.504510  1406986.68       0
10: 1.7794307 3.724905  1132513.33      70