0

我对 R 非常陌生,并且很难得到答案,所以我终于屈服于发布 - 所以提前道歉。

我正在使用遗传算法来优化对象的形状,并希望收集原型制作的中间步骤。我正在使用 genalg 的包允许监视功能来跟踪我可以很好地打印的数据。但我想将它存储在数据框中以供其他用途,并继续观察它是否会覆盖其他迭代。这是我的监控功能代码:

    monitor <- function(obj){

    #Make empty data frame in which to store data
    resultlist <- data.frame(matrix(nrow = 200, ncol = 10, byrow = TRUE))

    #If statement evaluating each iteration of algorithm
    if (obj$iter > 0){

    #Put results into list corresponding to number of iteration
    resultlist[,obj$iter] <- obj$population[which.min(obj$best),]}

    #Make data frame available at global level for prototyping, output, etc.
    resultlistOutput <<- resultlist}

我知道这在 for 循环中有效,基于搜索没有问题,所以我一定做错了什么或者 if 语法不能做到这一点?

提前真诚感谢您的宝贵时间。

4

1 回答 1

1

不确定你得到了什么错误,我猜你得到的只是上一次迭代的结果。monitor发生这种情况是因为您在每次调用函数时都覆盖了全局数据框。您应该首先以这种方式初始化resultlistOutput <<- data.frame(),然后执行以下操作:

monitor <- function(obj){

#Make empty data frame in which to store data
resultlist <- data.frame(matrix(nrow = 200, ncol = 10, byrow = TRUE))

#If statement evaluating each iteration of algorithm
if (obj$iter > 0){

#Put results into list corresponding to number of iteration
resultlist[,obj$iter] <- obj$population[which.min(obj$best),]}

#Make data frame available at global level for prototyping, output, etc.
# append the dataframe to the old result
resultlistOutput <<- rbind(resultlistOutput , resultlist)
}
于 2017-08-01T03:42:32.070 回答