# Include dataframe linear optimization in r

For a linear optimization problem I want to include a dataframe (d_ij) which has binary variables, 1 if customer i is located within the assignable distance of facility j, 0 otherwise. So unless d_ij = 1, the customer cannot be assigned to a facility. To create the model, I have introduced a binary variable X_ij (for customers) and Y_j (for the facilities)

The dataframe is constructed as follows:

#creating distance function
e <- function(i, j) {
customer <- data[i, ]
facility <- facility_locations[j, ]
(sqrt((customer$$x - facility$$x)^2 + (customer$$y - facility$$y)^2))
}

#with ifelse function, we model if the distance between consumer and facility is smaller than z =1, 0 otherwise

deltaframe <- data.frame(
customer=data$$ID, "j1" =ifelse(e(data$$ID, facility_locations$$ID==1)ID, facility_locations$$ID==2)ID, facility_locations$$ID==3)ID, facility_locations$$ID==4)ID, facility_locations$$ID==5)ID, facility_locations$$ID==6)ID, facility_locations$$ID==7)ID, facility_locations$$ID==8)ID, facility_locations$$ID==9)ID, facility_locations$$ID==10)ID, facility_locations$$ID==11)ID, facility_locations$$ID==12)ID, facility_locations$$ID==13)ID, facility_locations$$ID==14)ID, facility_locations$$ID==15)ID, facility_locations$$ID==16)ID, facility_locations$$ID==17)ID, facility_locations$$ID==18)ID, facility_locations$$ID==19)ID, facility_locations\$ID==20)<z,1,0)
)


Here z is a parameter, set to be the maximum distance a customer is willing to travel.

The constraint I try to model is $$x_{ij} <= d_{ij} * y_j$$ for all i and for all j

However, I do not know how to include this in r

• What R package are you using to build the model?
– prubin
Jul 11, 2022 at 15:16
• Can you please put a sample of the data frame data? And is z a vector? Jul 12, 2022 at 11:39

Hope this helps. You'll need to learn the basics of ompr, which is an awesome package. I use it regularly, including with Gurobi for large-scale optimizations.
• Thanks for the links! I'm working in ompr indeed and made it work through introducing a function, which i later include in a constraint in the model. delta <- function (i,j){ ifelse(e(i,j)<=z,1,0) } Jul 13, 2022 at 10:42