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
Define a function closest_to_3
that operates on a vector and returns the value in the vector that's closest to the third member:
closest_to_3 <- function(v) v[-3][which.min(abs( v[-3]-v[3] ))]
(The idiom v[-3]
deletes the 3rd member from v
.) Then apply this function to each row of your data frame:
apply(data, 1, closest_to_3)
#[1] 24 30 20