您可以尝试使用assignInNamespace
inside .onLoad
(未经测试),但就像 Adam H 在他的评论中所说的那样,听起来您正在以艰难的方式做事。
如果我正确理解了这个问题,那么您有一个导数表达式,并且您想在给定点评估该表达式,并计算该点的梯度,并计算该点的粗麻布。只需创建一个函数,该函数接受一个表达式和一个数值坐标向量来计算,然后让它吐出你想要的所有东西。像这样的东西:
#' Evaluate an expression, its derivative and its hessian
#'
#' Evaluates an expression, its derivative and its hessian at a given point.
#' @param expr An expression of derivatives
#' @param x A named numeric vector of coords to evaluate \code{expr} at
#' @param name String giving the name of the variable to differentiate by
#' @return A list with the following values
#' \itemize{
#' \item{value}{The value of \code{expr} evaluated at \code{x}.}
#' \item{gradient}{The value of the derivative of \code{expr} evaluated at \code{x}.}
#' \item{hessian}{The value of the hessian of \code{expr} evaluated at \code{x}.}
#' }
#' @examples
#' expr <- expression(sin(cos(x + y^2)))
#' x <- c(x = pi / 2, y = pi / 3)
#' eval_expr_and_calc_grad_and_hessian(expr, x, "x")
eval_expr_and_calc_grad_and_hessian <- function(expr, x, name = names(x)[1])
{
x <- as.list(x)
d_by_dname <- D(expr, name)
d2_by_dname2 <- D(d_by_dname, name)
list(
value = eval(expr, x),
gradient = eval(d_by_dname, x),
hessian = eval(d2_by_dname2, x)
)
}