Insert column vector at specific position in matrix dynamically

260 views Asked by At

i have to put a new vector (in this example zero-vector) into an exisiting matrix. The problem is that I have an iterative process and the positions and number of vectors to insert change. I have not been able to come up with a function that a) works and b) is efficient enough for huge amounts of data.

A non-dynamic approach using simply cbind() is

old <- matrix(1,10,10) #original matrix
vec <- matrix(5,10,1) #vector 1 to insert
vec2 <- matrix(8,10,1) #vector 2 to insert
old

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1    1    1    1    1    1    1    1    1     1
 [2,]    1    1    1    1    1    1    1    1    1     1
 [3,]    1    1    1    1    1    1    1    1    1     1
 [4,]    1    1    1    1    1    1    1    1    1     1
 [5,]    1    1    1    1    1    1    1    1    1     1
 [6,]    1    1    1    1    1    1    1    1    1     1
 [7,]    1    1    1    1    1    1    1    1    1     1
 [8,]    1    1    1    1    1    1    1    1    1     1
 [9,]    1    1    1    1    1    1    1    1    1     1
[10,]    1    1    1    1    1    1    1    1    1     1

#assume that the positions to insert are 4 and 8

goal <- cbind(old[,c(1:3)], 
              vec, 
              old[,4:6], #attention, now old column 6 is new column 7
              vec2, 
              old[,7:ncol(old)])

goal

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
 [1,]    1    1    1    5    1    1    1    8    1     1     1     1
 [2,]    1    1    1    5    1    1    1    8    1     1     1     1
 [3,]    1    1    1    5    1    1    1    8    1     1     1     1
 [4,]    1    1    1    5    1    1    1    8    1     1     1     1
 [5,]    1    1    1    5    1    1    1    8    1     1     1     1
 [6,]    1    1    1    5    1    1    1    8    1     1     1     1
 [7,]    1    1    1    5    1    1    1    8    1     1     1     1
 [8,]    1    1    1    5    1    1    1    8    1     1     1     1
 [9,]    1    1    1    5    1    1    1    8    1     1     1     1
[10,]    1    1    1    5    1    1    1    8    1     1     1     1

However, I could not think of something that works with both changing positions and number of vectors to insert. Any help is greatly appreciated, thank you very much.

2

There are 2 answers

2
G. Grothendieck On BEST ANSWER

cbind the vectors onto old and then reorder. If we knew that no were already sorted then we could replace sort(no) with no.

no <- c(4, 8)
vecs <- cbind(vec, vec2)
cbind(old, vecs)[, order(c(1:ncol(old), sort(no) - seq_along(no))) ]
0
yrx1702 On

Extending G. Grothendiecks approach and solving the ordering problem:

pos<-c(4,8)
pos<-pos-c(1:length(pos))
cbind(old, vec, vec2)[, order(c(1:ncol(old), c(pos)))]

Edit: Sorry, didn't see the edit of the answer above :)