Fill contingency table based on total variable

后端 未结 3 867
忘了有多久
忘了有多久 2021-01-23 03:07

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

3条回答
  •  独厮守ぢ
    2021-01-23 03:54

    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
    

提交回复
热议问题