I'm dealing with a data set of around 230k rows and 11 columns, and need to create a set of matrices (or a 3D array). The element of a given matrix is the sum of a certain column (let's say COST) of the data set when filtered on 3 criteria (let's say NAME, DATE, and NUMBER). Here's how I currently have this set up.
for(k in 1:length(names)) {
x <- matrix(0, nrow = length(dates), ncol = 20)
for(i in 1:length(dates)) {
for(j in 1:20) {
x[i, j] <- sum(claims[as.logical((data$NAME == names[k]) * (data$DATE == dates[i]) * (data$NUMBER == j)), 4])
}
}
assign(names[k], x)
}
Is there a way to accomplish this without using loops or if not, at least more efficiently?
Thanks!
Edit: Here's some test data I made up as requested. I only included columns that were necessary for this part of the code. I also decreased the number of columns for the matrices from 40 to 20 in the code above for testing purposes. dates and names are vectors needed for the for loops. test_input is the test data. test_output_market1 is the first matrix that would be created in the loops.
names:
c("Market1" "Market2" "Market3" "Market4" "Market5")
dates:
structure(c(18993 18994 18995 18996 18997 18998 18999
19000 19001 19002 19003 19004 19005 19006 19007 19008
19009 19010 19011 19012 19013 19014 19015 19016 19017
19018 19019 19020 19021 19022 19023) class = "Date")
test_input:
structure(list(DATE = structure(c(19021 19007 18994 19022
19010 19007 19007 18996 19012 19007) class = "Date") NUMBER = c(4
2 8 11 5 5 7 12 15 5) NAME = c("Market1" "Market3"
Market1 "Market1" "Market5" "Market4" "Market2" "Market3"
Market4 "Market5") COST = c(9384.3 93.23 6354.12 346.98
5743.48 845.73 3948.37 264.34 38790.24 8723.2)) class = "data.frame" row.names = c(NA
-10L))
test_output_market1:
structure(c(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9384.3
0 0 0 0 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