I'm running through an old piece of R code I had and making it run more efficiently as a leaning exercise.
I have a matrix which has 366 rows, representing each day of the year (probMatrix). I have another which has 7 rows, Representing each day of the week (from Monday). Both of these matrices have 10 columns.
The second matrix contains booleans for each day of the week that I want to multiply through the first matrix at the relevant elements (by row).
Finally, because Monday didn't occur until the fourth day of 2016, the second matrix needs to be offset by four so that it gets multiplied by the correct days.
I originally had a for loop that iterates through each day and sweeps the probability matrix using a vector containing the relevant indices of the first matrix that correspond to the first day of the week:
probMatrix <- matrix(rep((rep(1,366)), 10), ncol=10,byrow=TRUE)
booleanMatrix <- matrix(rep(c(0,0,0,0,1), 14), ncol=10, byrow=FALSE)
for (day in 1:7){
actualDay <- (day+3)
dayIndex <- c(seq(actualDay,366,7))
probMatrix[dayIndex,] <- sweep(probMatrix[dayIndex,],2,
as.numeric(booleanMatrix[day,]),"*")
}
However, as I mentioned above, this is quite an inefficient method. I would like something that runs a bit faster, as this sort of code runs through the script a lot.