Description Usage Arguments Details Value Author(s) See Also Examples

Finding the index of a sorted numeric vector whose element is closest to target.

1 2 3 |

`x` |
numeric vector to be optimized. The term abs(x[i])-target) is minimized. |

`target` |
Target value for |

`...` |
not used |

`interval` |
a vector containing the end-points of the interval to be searched for target. |

`lower` |
the lower end point of the interval to be searched. |

`upper` |
the upper end point of the interval to be searched. |

`maxiter` |
Maximum number of search iterations. Defaults to 100. |

`showiter` |
Boolean flag indicating whether the algorithm state should be printed at each iteration. Defaults to FALSE. |

This function can be applied similar to `optimize`

for cases, where the argument
to be optimized is an index instead of a continuous variable.
A binary search over the index is performed.

The function `x`

must be monotonic. If it is not strictly monotonic the returned
index (`$where`

) can be any of the indices with equal values.

The code is based on binsearch of the gtools package. In difference to the original code,
it returns always only one best estimate.

A list containing:

`call` |
How the function was called. |

`numiter` |
The number of iterations performed |

`flag ` |
One of the strings, "Found", "Between Elements", "Maximum number of iterations reached", "Reached lower boundary", or "Reached upper boundary." |

`where` |
One or two values indicating where the search terminated. |

`value` |
Value of the |

If vector is empty or upper boundary is lower than lower boundary, `where`

and `value`

are NA

Thomas Wutzler

1 2 3 4 5 6 7 8 9 10 11 12 | ```
# linear search is faster up with vectors to about 1e4 entries
x <- exp(seq(-10,100,length.out=1e4))
# with longer vectors, the binary search is superior
x <- exp(seq(-10,100,length.out=1e6))
# generate some sample indices that will be found by optimization
n <- 1e2
.where <- sample.int(length(x),n, replace=TRUE)
.val <- x[.where]*1.00001 # add some error, for exact matches use the faster function match
system.time( .where2 <- sapply(.val, function(vali){ which.min(abs(x-vali)) } ))
system.time( .where3 <- sapply(.val, function(vali){ twBinOptimize(x,vali)$where} ))
#Rprof(); .numiter3 <- sapply(.val, function(vali){ twBinOptimize(x,vali)$numiter} ); Rprof(NULL); summaryRprof()
``` |

Embedding an R snippet on your website

Add the following code to your website.

For more information on customizing the embed code, read Embedding Snippets.