I have two matrices 'times' and 'scaleFactor'. Each row in the 'times' matrix represents a person and the column represents the time at which some event occurred. The event changes the scale-up factor, which is available in the 'scaleFactor' matrix. For e.g., for person 1, the factor would be 1.2 in the time interval (1,3].
I want to create a matrix C having factors at each integer time point, where first column is time=0. I have written the code for generating matrix 'C', but I was wondering whether the 'for' loop can be avoided because the actual matrix is very large.
scaleFactor <- matrix(c(1,1.1,1.2,1.4,
1,1.3,1.4,1.6,
1,1.2,1.6,2.1),nrow = 3,ncol = 4, byrow = T)
times <- matrix(c(0,1,3,99,
0,2,5,99,
0,1,4,99),nrow = 3,ncol = 4,byrow = T)
> scaleFactor
[,1] [,2] [,3] [,4]
[1,] 1 1.1 1.2 1.4
[2,] 1 1.3 1.4 1.6
[3,] 1 1.2 1.6 2.1
> times
[,1] [,2] [,3] [,4]
[1,] 0 1 3 99
[2,] 0 2 5 99
[3,] 0 1 4 99
C <- matrix(0,nrow = 3,ncol = 6)
for (i in 1:ncol(C)){
indices <- max.col(i-1<=times,'first')
C[,i] <- scaleFactor[cbind(1:3,indices)]
}
> C
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1.1 1.2 1.2 1.4 1.4
[2,] 1 1.3 1.3 1.4 1.4 1.4
[3,] 1 1.2 1.6 1.6 1.6 2.1
Thank you so much for your help.
Edit: I later realized that the 'times' matrix can have non-integer time values. For such cases, the approach suggested by akrun works. Thanks!
times2 <- matrix(c(0,1.2,3.6,99,
0,2.1,5.3,99,
0,1,4,99),nrow = 3,ncol = 4,byrow = T)
> times2
[,1] [,2] [,3] [,4]
[1,] 0 1.2 3.6 99
[2,] 0 2.1 5.3 99
[3,] 0 1.0 4.0 99
# Matrix C would be -
> C
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1.1 1.2 1.2 1.4 1.4
[2,] 1 1.3 1.3 1.4 1.4 1.4
[3,] 1 1.2 1.6 1.6 1.6 2.1