R 错误:(全部(xi <= xj) && any(xi < xj)) { : missing value where TRUE/FALSE needed

问题描述 投票:0回答:1

我正在使用 R 编程语言。我正在尝试使用以下库来优化我编写的任意函数:https://cran.r-project.org/web/packages/nsga2R/nsga2R.pdf

首先我为此示例创建了一些数据:

#load library
library(dplyr)
library(nsga2R)

#create data for this example
# create some data for this example
a1 = rnorm(1000,100,10)
b1 = rnorm(1000,100,10)
c1 = sample.int(1000, 1000, replace = TRUE)
train_data = data.frame(a1,b1,c1)

然后,我定义了优化函数(7 个输入,4 个输出):

#define function

funct_set <- function (x) {
    x1 <- x[1]; x2 <- x[2]; x3 <- x[3] ; x4 <- x[4]; x5 <- x[5]; x6 <- x[6]; x[7] <- x[7]
    f <- numeric(4)
    
    
    #bin data according to random criteria
    train_data <- train_data %>%
        mutate(cat = ifelse(a1 <= x1 & b1 <= x3, "a",
                            ifelse(a1 <= x2 & b1 <= x4, "b", "c")))
    
    train_data$cat = as.factor(train_data$cat)
    
    #new splits
    a_table = train_data %>%
        filter(cat == "a") %>%
        select(a1, b1, c1, cat)
    
    b_table = train_data %>%
        filter(cat == "b") %>%
        select(a1, b1, c1, cat)
    
    c_table = train_data %>%
        filter(cat == "c") %>%
        select(a1, b1, c1, cat)
    
    
    
    #calculate  quantile ("quant") for each bin
    
    table_a = data.frame(a_table%>% group_by(cat) %>%
                             mutate(quant = ifelse(c1 > x[5],1,0 )))
    
    table_b = data.frame(b_table%>% group_by(cat) %>%
                             mutate(quant = ifelse(c1 > x[6],1,0 )))
    
    table_c = data.frame(c_table%>% group_by(cat) %>%
                             mutate(quant = ifelse(c1 > x[7],1,0 )))
    
    f[1] = mean(table_a$quant)
    f[2] = mean(table_b$quant)
    f[3] = mean(table_c$quant)
    
    
    #group all tables
    
    final_table = rbind(table_a, table_b, table_c)
    # calculate the total mean : this is what needs to be optimized
    
    f[4] = mean(final_table$quant)
    
    
    return (f);
}

然后,我运行优化代码:

#optimization
results <- nsga2R(fn=funct_set, varNo=7, objDim=4, lowerBounds=c(80,80,80,80, 100, 200, 300), upperBounds=c(120,120,120,120,200,300,400),
                  popSize=50, tourSize=2, generations=50, cprob=0.9, XoverDistIdx=20, mprob=0.1,MuDistIdx=3)

但这会返回以下错误:

Error in if (all(xi <= xj) && any(xi < xj)) { : 
  missing value where TRUE/FALSE needed

有谁知道产生的错误是否是由于我定义此问题的函数/数据的方式造成的?或者还有其他原因导致此错误产生吗?

谢谢

r function optimization constraints
1个回答
0
投票

我最近也遇到了同样的问题。就我而言,这是由于优化函数的返回向量为某些参数组合产生了 NA 值。将以下行添加到优化函数中可能会解决问题:

f = ifelse(is.na(f), Inf, f)

© www.soinside.com 2019 - 2024. All rights reserved.