I am trying to find the combination of columns "a" and "b" in table "brand_1" and "brand_2" that maximize my objective function "obj." How can I accomplish this without writing 4 for-loops?
Here is a simple code to illustrate my question. I also need to generalize it so that it works for any number of tables (not just "brand_1" and "brand_2") with each table will always have two columns ("a" and "b"). Thanks so much!
brand_1 <- data.frame(a = c(1, 3), b = c(5, 2))
brand_2 <- data.frame(a = c(5, 4), b = c(2, 1))
num_row <- nrow(brand_1) # where nrow(brand_1) = nrow(brand_2)
all_a1 <- vector()
all_b1 <- vector()
all_a2 <- vector()
all_b2 <- vector()
all_obj <- vector()
for (a1 in 1:num_row) {
for (b1 in 1:num_row) {
for (a2 in 1:num_row) {
for (b2 in 1:num_row) {
obj <- brand_1[a1, "a"] + brand_1[b1, "b"] + brand_2[a2, "a"] + brand_2[b2, "b"]
all_a1 <- c(all_a1, brand_1[a1, "a"])
all_b1 <- c(all_b1, brand_1[b1, "b"])
all_a2 <- c(all_a2, brand_2[a2, "a"])
all_b2 <- c(all_b2, brand_2[b2, "b"])
all_obj <- c(all_obj, obj)
}
}
}
}
out <- data.frame(all_a1, all_b1, all_a2, all_b2, all_obj)
