rnumbersclosest

Find next smaller and next larger values


I have two vectors:

smaller_array <- c(50, 60, 70, 75, 80, 85, 90, 95, 100, 105)

moneyness_cert <- c(105.8138,   105.7155,   105.4637,   104.5942,   105.0757,   105.316,    104.641,     
                    105.0637,   105.461,    104.971,    105.2471,   105.1348,   105.638,    105.8024,                                                               
                    105.592,    104.9338,   105.0133,   104.613,    104.9407,   105.0136,   107.2144,    
                    107.0112,   105.7793,   106.4742,   105.5703,   106.0615,   106.3446,   105.7296,    
                    105.1307,   104.6472,   103.6721,   104.607,    105.1265,   105.2077,   104.363,     
                    104.5036,   104.2205,   104.9135,   103.8404,   105.1506,   105.8887,   105.0894,    
                    104.3529,   103.0007,   103.0904,   103.334,    103.2959,   103.4819,   103.504,     
                    102.7641,   102.5911,   102.5386,   102.843,    103.8211,   102.3814,   105.265,     
                    104.3255,   104.1589,   105.6462,   107.0716,   106.5527,   104.655,    103.1285,    
                    102.3955,   102.8577) #length of vector is 65

I want to find for every moneyness_cert value the value which is closest to it in smaller_array. The so found values should be saved in a vector (e.g. "result_vector")

Example for the 64th element in moneyness_cert:
moneyness_cert = 102.3955

then return in smaller_array the value "100"
and save it in result_vector at place 64

I tried (which returned unuseful results); match.closest-function from MALDIquant-Package:

>     match.closest(x = moneyness_cert, table = sort(smaller_array, decreasing = F), tolerance = Inf, nomatch = NA)
 [1] 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
[26] 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
[51] 10 10 10 10  9 10 10 10 10 10 10 10 10  9 10

Another try was:

> apply(smaller_array, 1 , function(x) moneyness_cert - x)
Error in apply(smaller_array, 1, function(x) moneyness_cert - x) : 
  dim(X) must have a positive length

Via lapply it didn't work either.

Can anyone help me?

Thank you very much!


Solution

  • Try:

    sapply(moneyness_cert, function(x) smaller_array[which.min(abs(smaller_array - x))])
    

    Output:

    [1] 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105
    [34] 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 105 100 105 105 105 105 105 105 105 105 100 105
    

    Or directly for the 64th element:

    sapply(moneyness_cert, function(x) smaller_array[which.min(abs(smaller_array - x))])[64]
    
    # [1] 100