Reputation: 701
I want to find the row with minimum distance between the X and Y, and return the corresponding Z in R. Table 3 shows an example of this.
Table 1
X Z
10 0.655883255
20 0.511846995
10.5 0.995310138
Table 2
Y
11
12
13.5
23
Table 3
X Z
11 0.99
12 0.99
13.5 0.99
23 0.511
Upvotes: 0
Views: 494
Reputation: 3240
Not sure if you have to have this in a table format, but easy enough if they're vectors.
x <- c(10, 20, 10.5)
z <- c(0.655883255, 0.511846995, 0.995310138)
y <- c(11, 12, 13.5, 23)
z[unlist(lapply(y, function(t) which.min(abs(x-t))))]
# [1] 0.9953101 0.9953101 0.9953101 0.5118470
Upvotes: 3