Frameworker247 Frameworker247 - 1 month ago 5
R Question

From two vectors in R, find the min in the second vector greater than each value in the first

I have two vectors in R:

> x <- c(323, 344, 383, 404, 428, 444, 1447, 1466, 1492, 1512)
> y <- c(329, 389, 1453, 1465, 1498, 1511)


I need a data frame with x and the minimum in y greater than x, so this is the result set I'm looking for:

> data.frame(
x = c(323, 344, 383, 404, 428, 444, 1447, 1466, 1492, 1512),
y = c(329, 389, 389, 1453, 1453, 1453, 1453, 1498, 1498, NA)
)


I've tried to subset, something like:

> x_data_frame <- data.frame(a = x) #create the frame
> x_data_frame$b <- min(y[y > x]) #calculation


But of course, that doesn't work. Any ideas?

Answer

You can loop through x and construct a vector based on your condition:

data.frame(x, y = sapply(x, function(i) dplyr::na_if(min(y[y>i]), Inf)))

#      x    y
#1   323  329
#2   344  389
#3   383  389
#4   404 1453
#5   428 1453
#6   444 1453
#7  1447 1453
#8  1466 1498
#9  1492 1498
#10 1512   NA

Used the na_if() function from dplyr to replace Inf value with NA, you can ignore it if Inf value is fine for your analysis.

Comments