Home > front end >  R: how to double the entries in each row of a matrix and insert new rows
R: how to double the entries in each row of a matrix and insert new rows

Time:04-04

mylist <- list(matrix(c(1, 3, -1, 0, 2, 1), nrow = 2, byrow = TRUE),
               matrix(c(-2, 0, 10, 1, 2, 9, 2, 0, 0), nrow = 3, byrow = TRUE))
> mylist
[[1]]
     [,1] [,2] [,3]
[1,]    1    3   -1
[2,]    0    2    1

[[2]]
     [,1] [,2] [,3]
[1,]   -2    0   10
[2,]    1    2    9
[3,]    2    0    0

I have a list of matrices called mylist where the dimensions of the matrices can differ. For each matrix, I want to double the row values and insert it as a new row underneath. My desired output is as follows:

[[1]]
     [,1] [,2] [,3]
[1,]    1    3   -1
[2,]    2    6   -2
[3,]    0    2    1
[4,]    0    4    2

[[2]]
     [,1] [,2] [,3]
[1,]   -2    0   10
[2,]   -4    0   20
[3,]    1    2    9
[4,]    2    4   18
[5,]    2    0    0
[6,]    4    0    0

CodePudding user response:

In an lapply repeat each row index found using seq_len with nrow and multiply repeatedly by 1:2 exploiting recycling.

lapply(mylist, \(x) x[rep(seq_len(nrow(x)), each=2), ]*1:2)
# [[1]]
#      [,1] [,2] [,3]
# [1,]    1    3   -1
# [2,]    2    6   -2
# [3,]    0    2    1
# [4,]    0    4    2
# 
# [[2]]
#      [,1] [,2] [,3]
# [1,]   -2    0   10
# [2,]   -4    0   20
# [3,]    1    2    9
# [4,]    2    4   18
# [5,]    2    0    0
# [6,]    4    0    0

CodePudding user response:

You can use rbind but you need to permute rows to get multiplied row beneath:

lapply(
  mylist,
  function(x){
    rbind(x, x * 2)[as.vector(t(matrix(seq_len(nrow(x) * 2), ncol = 2))),]
  }     
)

[[1]]
     [,1] [,2] [,3]
[1,]    1    3   -1
[2,]    2    6   -2
[3,]    0    2    1
[4,]    0    4    2

[[2]]
     [,1] [,2] [,3]
[1,]   -2    0   10
[2,]   -4    0   20
[3,]    1    2    9
[4,]    2    4   18
[5,]    2    0    0
[6,]    4    0    0

CodePudding user response:

Another base R approach which also utilises the rbind function with do.call.

lapply(mylist, function(x) 
  do.call(rbind, lapply(1:nrow(x), function(i) rbind(x[i, ], x[i,]*2))))

[[1]]
     [,1] [,2] [,3]
[1,]    1    3   -1
[2,]    2    6   -2
[3,]    0    2    1
[4,]    0    4    2

[[2]]
     [,1] [,2] [,3]
[1,]   -2    0   10
[2,]   -4    0   20
[3,]    1    2    9
[4,]    2    4   18
[5,]    2    0    0
[6,]    4    0    0
  • Related