I have a list of stores and I have a product (apples). I ran a system of linear equations to get the column \'var\'; this value represents the amount of apples you will
I bet there are simpler ways of doing this but this one works.
The function fun
outputs a result identical
to the expected one.
fun <- function(DF){
n <- nrow(DF)
mat <- matrix(0, nrow = n, ncol = n)
VAR <- DF[["var"]]
neg <- which(DF[["var"]] < 0)
for(k in neg){
S <- 0
Tot <- abs(DF[k, "var"])
for(i in seq_along(VAR)){
if(i != k){
if(VAR[i] > 0){
if(S + VAR[i] <= Tot){
mat[k, i] <- VAR[i]
S <- S + VAR[i]
VAR[i] <- 0
}else{
mat[k, i] <- Tot - S
S <- Tot
VAR[i] <- VAR[i] - Tot + S
}
}
}
}
}
colnames(mat) <- paste0("ship_to_", DF[["store"]])
cbind(DF, mat)
}
out <- fun(df)
identical(output, out)
#[1] TRUE