Title: | Combined Evaluation and Split Access of Functions |
---|---|
Description: | Some R functions, such as optim(), require a function its gradient passed as separate arguments. When these are expensive to calculate it may be much faster to calculate the function (fn) and gradient (gr) together since they often share many calculations (chain rule). This package allows the user to pass in a single function that returns both the function and gradient, then splits (hence 'splitfngr') them so the results can be accessed separately. The functions provided allow this to be done with any number of functions/values, not just for functions and gradients. |
Authors: | Collin Erickson |
Maintainer: | Collin Erickson <[email protected]> |
License: | GPL-3 |
Version: | 0.1.2 |
Built: | 2024-11-16 03:33:25 UTC |
Source: | https://github.com/collinerickson/splitfngr |
Access a list of values separately but calculate them together. This function generalizes grad_share for any number of functions.
fngr(func, evalForNewX = TRUE, recalculate_indices = c(), check_all = FALSE)
fngr(func, evalForNewX = TRUE, recalculate_indices = c(), check_all = FALSE)
func |
Function that returns a list of values |
evalForNewX |
Should the function reevaluate for any new x? Recommended. |
recalculate_indices |
Indices for which the values should be recalculated. Ignored if evalForNewX is true. Use this if you don't want to pass x to dependent functions, or if you know other indices won't need to be recalculated. |
check_all |
Should it check that the accessed values were calculated at the current input? Ignored if evalForNewX is true. Will give a warning but still return the stored value. |
An environment where the function values are calculated.
tfunc <- function(x) {list(x+1, x+2, x+3, x+4, x+5)} f <- fngr(tfunc) f(1)(0) f(3)(0) f(3)(1) f(1)(23.4) f(4)() # Use same function but only recalculate when first value is called g <- fngr(tfunc, evalForNewX = FALSE, recalculate_indices = c(1)) g1 <- g(1) g3 <- g(3) g1(1) g3(1) g3(11) # This won't be give expected value g1(11) # This updates all values g3(11) # This is right
tfunc <- function(x) {list(x+1, x+2, x+3, x+4, x+5)} f <- fngr(tfunc) f(1)(0) f(3)(0) f(3)(1) f(1)(23.4) f(4)() # Use same function but only recalculate when first value is called g <- fngr(tfunc, evalForNewX = FALSE, recalculate_indices = c(1)) g1 <- g(1) g3 <- g(3) g1(1) g3(1) g3(11) # This won't be give expected value g1(11) # This updates all values g3(11) # This is right