简体   繁体   中英

How to find the best possible solution? For-loop [r]

I have written this code:

P<-4000000 #population
j<-4 #exposures
budget<-7000 #Euros
vehicles<-data.frame(A1=c(2000001,1700000,1619200),A2=c(2500000,1900000,1781120),Price=c(2000,1500,1000)) #A1: Audience1, A2: Audience2 & Price-insertion


end.i<-FALSE
for(i in seq(4,1000,1)){

  for(k in 1:nrow(vehicles)){

    R1=vehicles$A1[k]/P;R2=vehicles$A2[k]/P
    shape1=((R1)*((R2)-(R1)))/(2*(R1)-(R1)*(R1)-(R2));shape1
    shape2=(shape1*(1-(R1)))/(R1);shape2

    t <- dbetabinom.ab(1:i, size = i, shape1 = shape1, shape2 = shape2)

    print(t[j])
    print(paste(k,"vehicles",sep=" "))
    print(paste(i,"insertions", sep=" "))
    price<-i*vehicles$Price[k]
    print(paste(price,"Euros",sep=" "))

    if((i*vehicles$Price[k])<=budget& t[j]>=0.024 & t[j]<=0.025){end.i<-TRUE;break;}

  };

  if (end.i) break;

}

This code allows extracting the number of insertions (i) necessary to reach 'X individuals (t[j] probability x population) exposed j times' (my objective).

However, the code ends when it reachs a solution. I would be interested in knowing how to program the code to estimate all the possible solutions, and choose one that would also allow to minimize the cost of the insertions (vehicles$Price[k] xi).

Kind regards,

Majesus

Try this. Just append the solutions to a data frame (called out_put in this case)

P<-4000000 #population
j<-4 #exposures
budget<-7000 #Euros
vehicles<-data.frame(A1=c(2000001,1700000,1619200),A2=c(2500000,1900000,1781120),Price=c(2000,1500,1000)) #A1: Audience1, A2: Audience2 & Price-insertion

out_put = data.frame(TJ = NA,Vehicles = NA, Insertions = NA,Price_Euros = NA)

for(i in seq(4,1000,1)){
  for(k in 1:nrow(vehicles)){
    R1=vehicles$A1[k]/P;R2=vehicles$A2[k]/P
    shape1=((R1)*((R2)-(R1)))/(2*(R1)-(R1)*(R1)-(R2))
    shape2=(shape1*(1-(R1)))/(R1)

    t <- dbetabinom.ab(1:i, size = i, shape1 = shape1, shape2 = shape2)
    price<-i*vehicles$Price[k]    

    out_put = rbind(out_put,c(t[j],k,i,price))
  }
}

out_put = out_put[2:nrow(out_put),]
rownames(out_put) = NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM