lsangha
lsangha

Reputation: 39

Get column name of the nearest or matching value in a column


head(mtcars)

                  mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

I want two new columns. near_wt which has the value same or near to the wt column.

I got this using

mtcars$near_wt <- mtcars[, -col][cbind(1:nrow(mtcars),
                                     max.col(-abs(mtcars[, col] - mtcars[, -col])))]

This works. The next thing I need is the column name from which each value of "near_wt" comes.

Upvotes: 0

Views: 45

Answers (1)

Kra.P
Kra.P

Reputation: 15153

Does col is 6? If so, you may try this way. For convenience, I define x as

x <- cbind(1:nrow(mtcars),max.col(-abs(mtcars[, col] - mtcars[, -col])))

Then,

mtcars$near_wt <- mtcars[, -6][x]
mtcars$near_wt_name <- names(mtcars[-6])[x[,2]]

head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb near_wt near_wt_name
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4    3.90         drat
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4    3.90         drat
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1    1.00           am
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1    3.08         drat
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2    3.15         drat
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1    3.00         gear

Upvotes: 2

Related Questions