Search code examples
rlistmatrixlapplylag

dividing first row of each matrix in list of matrices by the lagged sum of all rows in each matrix of a list matrices


I have a list of 100 - 3 x 51 matrices in r and would like to divide the first row of each matrix in the list by the lagged (n=2) sum of all rows in each corresponding matrix iteratively corresponding with the lag. I know how to achieve this within the same row within a list of vectors with the following code

Example_List2 <- lapply(Example_List1,function(x){x/lag(x,n=2)})

My attempt at the 3 row list is coded below. I would ultimately like to make this the replacement first row of a new DB and repeat this process for each row with dif lags. My attempted code is

List2 <- List1
lapply(List2, `[`,1,) <- lapply(List1,function(x){lapply(x, `[`,1,)/lag(colSums(x),n=2)})
lapply(List2, `[`,2,) <- lapply(List1,function(x){lapply(x, `[`,2,)/lag(colSums(x),n=3)})
lapply(List2, `[`,3,) <- lapply(List1,function(x){lapply(x, `[`,3,)/lag(colSums(x),n=4)})

Solution

  • We may use

    library(rbindlist)
    List2 <- lapply(List1, \(x) x/do.call(rbind, shift(colSums(x), n = 2:4)))
    

    For the second case

    List3 <- lapply(List1, \(x) { 
          n1 <- 2:4
         x1 <- colSums(x)
         x2 <- x
       for(i in seq_along(n1)) {
          x2[i,] <- shift(x[i,], n = n1[i], type = "lead")}
            colSums(x2)/x1
    })
    

    data

    set.seed(24)
    List1 <- replicate(100, matrix(rnorm(3*51), nrow = 3), simplify = FALSE)