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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With