So I have a 1256 by 5 matrix.
> head(retmatx12.30.3)
AMT HON KO
[1,] -0.006673489 -0.001292867 -0.0033654493
[2,] 0.004447249 0.002848406 0.0082009877
[3,] 0.001789891 0.002754232 -0.0035886573
[4,] -0.003479321 0.002231823 0.0024011113
[5,] -0.006605786 0.015159190 -0.0002394852
[6,] -0.002375004 -0.008267790 -0.0100625938
NEM NVAX
[1,] -0.034023392 -0.023255737
[2,] 0.016436786 0.007936468
[3,] 0.009529404 0.031496102
[4,] 0.046052588 0.007633549
[5,] -0.031446425 0.037878788
[6,] -0.001694084 0.036496350
I want to apply a function I've made to rows 1-126, then 2-127, and so on. The function is a block of matrix algebra that uses a matrix and a few vectors. Is it wise to somehow break the larger matrix into 1,131 126 by 5 matrices, and apply the function over each (hopefully at once). Or, some sort of application of apply?
Any help is greatly appreciated. Thanks
CodePudding user response:
The actual numbers in the matrix are immaterial, so I'll use much smaller data to demonstrate one method, and a simple function to demonstrate the rolling calculation:
m <- matrix(1:24, nrow=8)
somefunc <- function(x) x %*% seq(ncol(x))
wid <- 4 # 126
somefunc(m[1:4,])
# [,1]
# [1,] 70
# [2,] 76
# [3,] 82
# [4,] 88
somefunc(m[2:5,])
# [,1]
# [1,] 76
# [2,] 82
# [3,] 88
# [4,] 94
The actual rolling work:
lapply(seq(nrow(m) - wid 1), function(i) somefunc(m[i - 1 seq(wid),]))
# [[1]]
# [,1]
# [1,] 70
# [2,] 76
# [3,] 82
# [4,] 88
# [[2]]
# [,1]
# [1,] 76
# [2,] 82
# [3,] 88
# [4,] 94
# [[3]]
# [,1]
# [1,] 82
# [2,] 88
# [3,] 94
# [4,] 100
# [[4]]
# [,1]
# [1,] 88
# [2,] 94
# [3,] 100
# [4,] 106
# [[5]]
# [,1]
# [1,] 94
# [2,] 100
# [3,] 106
# [4,] 112
where the first element of the output is from rows 1-4, then 2-5, then 2-6, etc.