1

Data Frame:

 set.seed(90)
 df <- data.frame(id = 1:10, values = round(rnorm(10),1))
    id values
 1   1    0.1
 2   2   -0.2
 3   3   -0.9
 4   4   -0.7
 5   5    0.7
 6   6    0.4
 7   7    1.0
 8   8    0.9
 9   9   -0.6
 10 10    2.4

Table:

 table <- data.frame(values = c(-2.0001,1.0023,0.0005,1.0002,2.00009), final_values = round(rnorm(5),2))

    values final_values
 1 -2.00010        -0.81
 2  1.00230        -0.08
 3  0.00050         0.87
 4  1.00020         1.66
 5  2.00009        -0.24

I need to replace the values in data frame based on the closest match of the values in table.

Final Output:

    id final_values
 1   1    0.87
 2   2    0.87
 3   3   -0.08
 4   4   -0.08
 5   5    1.66
 6   6    0.87
 7   7    1.66
 8   8    1.66
 9   9   -0.08
 10 10   -0.24

What is the best way to do this with base R?

Leonhardt Guass
  • 773
  • 7
  • 24
  • This is essentially a dupe of http://stackoverflow.com/q/19957725/ though I think the answers there could use an update. – Frank Mar 15 '17 at 20:24

1 Answers1

3

Here is a way and you can overwrite the result back to df:

sapply(df$values, function(x) table$final_values[which.min(abs(x - table$values))])
[1]  0.87  0.87 -0.08 -0.08  1.66  0.87  1.66  1.66 -0.08 -0.24
JasonWang
  • 2,414
  • 11
  • 12