Reputation: 693
Suppose I have the following matrix
A = diag(5)
A
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 0 0 0
[2,] 0 1 0 0 0
[3,] 0 0 1 0 0
[4,] 0 0 0 1 0
[5,] 0 0 0 0 1
and I want to add the first column of the matrix A
in the new_A
(for n
times, suppose that n = 3
, but in my case, n
can be bigger)
new_A
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 1 1 1 0 0 0 0
[2,] 0 0 0 0 1 0 0 0
[3,] 0 0 0 0 0 1 0 0
[4,] 0 0 0 0 0 0 1 0
[5,] 0 0 0 0 0 0 0 1
How can I add the first column of the A
for n
times in the new_A
automatically?
Upvotes: 0
Views: 44
Reputation: 389135
Repeat 1 n
times and append the remaining columns.
n = 3
A[, c(rep(1, n + 1), 2:ncol(A))]
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#[1,] 1 1 1 1 0 0 0 0
#[2,] 0 0 0 0 1 0 0 0
#[3,] 0 0 0 0 0 1 0 0
#[4,] 0 0 0 0 0 0 1 0
#[5,] 0 0 0 0 0 0 0 1
Upvotes: 1