在 objective 函数中使用 sapply(或 apply)进行优化;不再识别列表元素中的对象

Using sapply (or apply) inside objective function for optim ; object in list element no longer recognized

我想使用基于元素列表的 objective 函数,每个元素都是在数据帧 (df) 上应用函数的结果((函数是 df 的方差观察'"measure"))。也就是说,我有一个 dfs 列表。我自然希望 sapply 我的函数覆盖 dfs 列表。

没有sapply这第一个块有效。它用于单个df,所以没有sapply命令,函数是min.RSS (标准误差的计算,我们希望 optim 最小化)

#setup dfs
list_dat <- array(list(), dim=c(2,1))
list_dat[[1]] =data.frame(x=c(1,2,3,4,5,6,7,8), 
               y=c(1,3,5,6,8,12,15,19))
list_dat[[2]] =data.frame(x=c(1,2,3,4,5,6), 
                          y=c(1,3,5,6,8,12))
#define objective fn
min.RSS <- function(data, par) {
  with(data, sum((par[1] + par[2] * x - y)^2))
  }

#optimize : find minimum given starting values, feeding in the first element, namely the df 
result <- optim(c(0.5,0.5), min.RSS,   data = list_dat[[1]])

下面的不行,一个包含sapply的块,回来报错

Error in eval(expr, envir, enclos) : object 'x' not found

谁能知道为什么?

#define new objective function based only on the first element, and optimize
min.RSS <- function(data, par) {
  sapply(list, function(data) with(data, sum((par[1] + par[2]* x - y)^2)))[[1]]
  }
result <- optim(c(0.5,0.5), min.RSS,   data = list_dat) # optimize, feeding in the list of (2) dfs

为了解释我不明白的地方,只使用没有 optim 的 sapply 就可以按预期工作。我将正在优化的参数 par[1] par[2] 更改为标量。也就是说,以下也 works

list2 <- sapply(list_dat, function(data) with(data, sum((1 + 2 * x - y)^2)))
  1. list_dat 不是一个列表,它是一个列表数组。
  2. 您对 min.RSS 的定义将 data 定义为其参数,但随后引用 list
#  You don't really need to preallocate the list, but if you insist
list_dat <- vector(length=2, mode='list')
list_dat[[1]] =data.frame(x=c(1,2,3,4,5,6,7,8), 
                          y=c(1,3,5,6,8,12,15,19))
list_dat[[2]] =data.frame(x=c(1,2,3,4,5,6), 
                          y=c(1,3,5,6,8,12))


min.RSS <- function(list, par) {
    sapply(list, function(data) with(data, sum((par[1] + par[2]* x - y)^2)))[[1]]
}

 result <- optim(c(0.5,0.5), min.RSS,   list = list_dat)