简体   繁体   中英

Lookup values in a data table in r

So I want to be able to find the ScoreLU value based on the df table. For example the value of 1.3730682 in DSCRpd should return the ScoreLU value of 60 ie nearest value. Yes, just like the vlookup function in excel. Is there an r package that can help or has anyone solved this issue another way.

I have 2 data tables, the first one called df that contains values

[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

The second table is where the lookup values are stored as:

[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

Using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM