Tilo
Tilo

Reputation: 429

Setting vector X to nearest value of vector Y among other 2 vectors

Dataframe is

**Y    Y1    Y2     

58   65    59     
60   61    61.4   
56   52    78     
64   78    80** 

And My expected output should be as given below, where X should reference Y and choose value among Y1,Y2 which-soever is nearer.
X is my expected new output column and Y is the reference one.

Y    Y1    Y2     X

58   65    59     59
60   61    61.4   61
56   52    78     52
64   78    80     78

Upvotes: 2

Views: 34

Answers (1)

LAP
LAP

Reputation: 6685

You can use ifelse() to compare the difference between the two vector values and the initial values, and choose the lower:

df <- data.frame(Y = c(58,60,56,64),
                 Y1 = c(65,61,52,78),
                 Y2 = c(59,61.4,78,80))

df$X <- with(df, ifelse(abs(Y1-Y) < abs(Y2-Y), Y1, Y2))

   Y Y1   Y2  X
1 58 65 59.0 59
2 60 61 61.4 61
3 56 52 78.0 52
4 64 78 80.0 78

Edit: As @RuiBarradas pointed out, the comparison should probably be done on absolute values. I've changed the ifelse() condition to account for this.

Upvotes: 2

Related Questions