Home > Software engineering >  dividing first row of each matrix in list of matrices by the lagged sum of all rows in each matrix o
dividing first row of each matrix in list of matrices by the lagged sum of all rows in each matrix o

Time:12-21

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)})

CodePudding user response:

We may use

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

data

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

CodePudding user response:

Try this.

lapply(List1, \(x) {
  u <- 1:2
  x[1, -u] <- x[1, -u]/colSums(x[, -u])
  # x[1, u] <- NA_real_  ## uncomment if you want NA for x[1, 1:2]
  x
})
# [[1]]
#      [,1] [,2]      [,3]       [,4]       [,5]
# [1,]    1    4 0.2916667  0.3030303  0.3095238
# [2,]    2    5 8.0000000 11.0000000 14.0000000
# [3,]    3    6 9.0000000 12.0000000 15.0000000
# 
# [[2]]
#       [,1] [,2]      [,3]       [,4]       [,5]
# [1,]    1    4 0.2916667  0.3030303  0.3095238
# [2,]    2    5 8.0000000 11.0000000 14.0000000
# [3,]    3    6 9.0000000 12.0000000 15.0000000
# 
# [[3]]
#       [,1] [,2]      [,3]       [,4]       [,5]
# [1,]    1    4 0.2916667  0.3030303  0.3095238
# [2,]    2    5 8.0000000 11.0000000 14.0000000
# [3,]    3    6 9.0000000 12.0000000 15.0000000

Data:

List1 <- replicate(3, matrix(1:15, 3, 5), simplify=FALSE)
  • Related