Reputation: 33
Hi I have a df as below
**name | min_date | max_date | act_val | A | B | C | D
sam 2016-06-01 2016-06-27 30724 38115 635 2541 26
fred 2016-06-01 2016-06-27 29270 38115 635 2541 26
hays 2016-06-01 2016-06-27 29270 38115 635 2541 26
prem 2016-06-01 2016-06-27 700 38115 635 2541 26
cains 2016-06-01 2016-06-27 24 38115 635 2541 26
alan 2016-06-01 2016-06-27 28 38115 635 2541 26
vincy 2016-06-01 2016-06-27 3000 38115 635 2541 26
i want compare "act_val" with all other columns in order to get nearest >variable name i.e in row 1 , 30724 is near to value in A (30724 ~= 38115)
| name | min_date | max_date | act_val | A | B | C | D | near_column
sam 2016-06-01 2016-06-27 30724 38115 635 2541 26 A
fred 2016-06-01 2016-06-27 29270 38115 635 2541 26 A
hays 2016-06-01 2016-06-27 29270 38115 635 2541 26 A
prem 2016-06-01 2016-06-27 700 38115 635 2541 26 B
cains 2016-06-01 2016-06-27 24 38115 635 2541 26 D
alan 2016-06-01 2016-06-27 28 38115 635 2541 26 D
vincy 2016-06-01 2016-06-27 3000 38115 635 2541 26 C
Thanks in advance
Upvotes: 2
Views: 41
Reputation: 887193
We can use max.col
df1$near_column <- names(df1)[-1][ max.col(-abs(df1[-1]- df1[,1]))]
df1$near_column
#[1] "A" "A" "B" "D" "D" "C"
Upvotes: 1