Closest value to a specific column in R

  • A+
Category:Languages

I would like to find the closest value to column x3 below.

data=data.frame(x1=c(24,12,76),x2=c(15,30,20),x3=c(45,27,15)) data   x1 x2 x3 1 24 15 45 2 12 30 27 3 76 20 15 

So desired output will be

Closest_Value_to_x3    24    30    20 

Please help. Thank you

 


Use max.col(-abs(data[, 3] - data[, 1:2])) to find the column positions of the closest values and use this result as part of a matrix to subset your data. The matrix is returned by cbind.

data[, 1:2][cbind(1:nrow(data),                   max.col(-abs(data[, 3] - data[, 1:2])))] #[1] 24 30 20 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: