Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create n*n matrix from n-1*n matrix by adding diagonal elements as 1 in R

Tags:

r

matrix

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
like image 526
Triparna Poddar Avatar asked Dec 18 '22 12:12

Triparna Poddar


2 Answers

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))
like image 140
tmfmnk Avatar answered Jan 26 '23 00:01

tmfmnk


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)
like image 35
jay.sf Avatar answered Jan 25 '23 23:01

jay.sf