I have a dataframe containing cost data and a separate list of matrices that state how each type of cost should be allocated. For the sake of explanation, I'll make some dummy data.
library(tidyverse)
# here is my list of cost allocation matrices
matrList <- list(A = cbind(runif(3),runif(3),runif(3)),
B = cbind(runif(3),runif(3),runif(3)),
C = cbind(runif(3),runif(3),runif(3))) %>%
lapply(function(x){
rownames(x) <- c("x","y","z")
colnames(x) <- c("p","q","r")
x <- x/sum(x)
})
# and here is my cost data
mydf <- data.frame(val = runif(8,0,100),
lookup = c("A","C","B","B","C","B","C","A"))
So each cost is either type A, type B or type C. For each of these types, there is a 3x3 matrix that sums to 1 that states how that cost should be allocated.
I've managed to botch a kind of left_join
that adds a column to the dataframe containing the appropriate matrices
mydf <- mydf %>%
mutate(propMatrix = lapply(lookup, function(x) matrList[[x]]))
This seems to keep the structure of the matrices - great. Only now I want to multiply each propMatrix
by the corresponding val
in the dataframe to give me matrices containing the actual allocated costs rather than just the proportions. Optimistically, I thought something simple like mutate(valMatrix = val*propMatrix)
might work but no.
Does anyone have any smart ideas? I suppose it could be done in a loop as a last resort, but it's not hugely practical given the size of my actual data. I also don't think it's practical to abandon approach of having matrices within the dataframe and put it in long form with replicated rows since each matrix is ~600x100.
Any thoughts much appreciated.
Thanks in advance, James