如何将参数传递给另一个函数的参数

时间:2019-05-23 06:31:04

标签: r function parameters

我有一个目标函数f(x,d),其中x是两个变量(x1,x2)的向量,而d是点的Nx2矩阵。 f(x)是一个距离函数,计算从x到d中所有点的一定距离。

我正在尝试创建一个梯度下降函数来计算函数的最小值。首先,我创建了一个梯度函数,该函数取决于给定的外部参数d(请参见下文)。

test03SecondCaseButRunsThird() { //test code }

然后,我如下创建了梯度下降函数。我想使该函数尽可能通用,以便可用于其他目标函数。

# Customers location from an external file (100 customers)
locations = read.csv(file = 'locations.csv')

# Gradient of my objective function is:
obj_fun.grad <- function(x,d) {
  dx <- 2*(x[1] - d$x)/((x[1] - d$x)^2 + 1) 
  dy <- 2*(x[2] - d$y)/((x[2] - d$y)^2 + 1)
  s <- c(sum(dx),sum(dy))

  return (s)
}

现在,我想调用grad.descent函数,如果locations文件作为附加参数传递给了梯度函数,则传递该函数:

grad.descent = function(grad.function, x0, max.iter=200, step.size=0.05, stopping.deriv=0.01,...) { # Calculating the length of the initial vector n = length(x0) # Create a matrix where the coordinates of different steps will be stored xmat = matrix(0, nrow=n, ncol=max.iter) # Initial guess is the starting point xmat[,1] = x0 for (k in 2:max.iter) { # Calculate the gradient, that depends on locations of customers grad.cur = grad.function(xmat[,k-1], d=d) # Check whether gradient is below the given threshold if (sqrt(t(grad.cur)%*%grad.cur) < stopping.deriv) { k = k-1; break } # Move in the opposite direction of the grad xmat[,k] = xmat[,k-1] - step.size*grad.cur } # Remove unused positions xmat = xmat[,1:k] # Return: 1) optimum position, 2) list of all positions, 3) number of iterations return(list(x=xmat[,k], xmat=xmat[,1:k], k=k)) }

但是,出现以下错误:

  

fgrad(xmat [,k-1],d = d)错误:找不到对象'd'

1 个答案:

答案 0 :(得分:0)

R告诉您未找到对象d,因为您从未告诉过对象d是什么。

最简单的解决方法是将grad.descent函数中的for循环内的第一行替换为以下行:

grad.cur = grad.function(xmat[,k-1], d = locations)

这样,函数grad.function知道它应该将数据帧locations作为其第二个输入d

请注意,这是有效的,因为R使用词法作用域。您可以找到更多信息here