运行程序时出现错误。它使用的是genalg软件包,但是这个软件包不是问题,因为我遇到了多个软件包的问题。我相信if语句中存在错误,我不确定如何使它运行并找到正确的答案。错误是
Error in evalVals[object] <- evalFunc(population[object, ]) :
replacement has length zero
这是我的代码:
#initilaize library
library(genalg)
#insert data
#set objective
#minimize the sume of x1,x2,x3,x4,x5,x6
datat = data.frame(city1 = c(0, 10, 20, 30, 30, 20),
city2 = c(10, 0, 25, 35, 15, 30),
city3 = c(20, 25, 0, 15, 30, 20),
city4 = c(30, 35, 15, 0, 15, 25),
city5 = c(30, 15, 30, 15, 0, 14),
city6 = c(20, 30, 20, 25, 14, 0))
coeff = c(0, 10, 15, 15, 14, 0)
#constraints
#add in a penalty to run function
evalFunc = function(x = c()){
# x1 + x2 >= 1
x12 <- c(1, 1, 0, 0, 0, 0)
# x2 + x4 + x6 >= 2
x246 <- c(0, 1, 0, 1, 0, 1)
# x3 + x4 >= 1
x34 <- c(0, 0, 1, 1, 0, 0)
# x1 + x2 + x3 + x4 + x5 + x6 >= 1
xtot <- c(1, 1, 1, 1, 1, 1)
# x4 + x5 + x6 >= 2
x456 <- c(0, 0, 0, 1, 1, 1)
# x2 + x4 + x5 + x6 >= 3
x2456 <- c(0, 1, 0, 1, 1, 1)
# x5 + x6 >= 1
x56 <- c(0, 0, 0, 0, 1, 1)
objt <- sum(x*xtot)
con12 <- sum(x*x12)
con246 <- sum(x*x246)
con34 <- sum(x*x34)
con456 <- sum(x*x456)
con2456 <- sum(x*x2456)
con56 <- sum(x*x56)
minnot <- 0
min1 <- 1
min2 <- 2
# objt >= minnot
# con12 >= minnot
# con246 >= min1
# con34 >= minnot
# con456 >= min1
# con2456 >= min2
# con56 >= minnot
print(x)
c12 <- c(2, 0, 0, 0, 0, 0)
y = sum(x*c12)
print(y)
if (objt <= minnot) {
return(400)}#xtot <- c(100, 100, 100, 100, 100, 100)#multiplication is causing error
else if (con12 <= minnot) {
return(400)}#x12 <- c(100, 100, 100, 100, 100, 100) #how do I fix it?
else if (con246 <= min1) {
return(400)} #x246 <- c(100, 100, 100, 100, 100, 100)
else if (con34 <= minnot) {
return(400)} # x34 <- c(100, 100, 100, 100, 100, 100)
else if (con456 <= min1) {
return(400)} #x456 <- c(100, 100, 100, 100, 100, 100)
else if (con2456 <= min2) {
return(400)} #x2456 <- c(100, 100, 100, 100, 100, 100)
else if (con56 <= minnot) {
return(400)} #x56 <- c(100, 100, 100, 100, 100, 100)
}
#create function to create shortest path
gamod = rbga.bin(size = 6,
popSize = 200,
iters = 300,
mutationChance = .01,
elitism = 1,
evalFunc = evalFunc)
#run function
#display results
非常感谢您的协助!
最佳答案
添加:
else {
return(0)} # Replace 0 by what you want
在
if
语句的末尾。
关于r - “Replacement Length Equal to Zero”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48848582/