For example I have a 2*3 matrix
[,1] [,2] [,3]
[1,] 2 4 6
[2,] 3 5 7
I want to have a 3*3 matrix inserting 1 in the diagonal In R The output :
[,1] [,2] [,3]
[1,] 1 4 6
[2,] 2 1 7
[3,] 3 5 1
One option could be:
mat_new <- `diag<-`(matrix(ncol = ncol(mat), nrow = nrow(mat) + 1, 0), 1)
mat_new[mat_new == 0] <- mat
[,1] [,2] [,3]
[1,] 1 4 6
[2,] 2 1 7
[3,] 3 5 1
Or a variation on the original idea (proposed by @Henrik):
mat_new <- diag(ncol(mat))
mat_new[mat_new == 0] <- mat
Sample data:
mat <- structure(2:7, .Dim = 2:3, .Dimnames = list(c("[1,]", "[2,]"),
NULL))
Using append
.
unname(mapply(function(x, y) append(x, 1, y), as.data.frame(m), 1:ncol(m) - 1))
# [,1] [,2] [,3]
# [1,] 1 4 6
# [2,] 2 1 7
# [3,] 3 5 1
Or using replace
.
replace(diag(3), diag(3) < 1, m)
# [,1] [,2] [,3]
# [1,] 1 4 6
# [2,] 2 1 7
# [3,] 3 5 1
Data:
m <- structure(2:7, .Dim = 2:3)
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