Reputation: 651
I have matrix of size NxK called A and a vector/matrix of size 1xK called V.
V only consists of elements of zero and ones, an example could be something like this:
V=matrix(c(0,1,0,0,0,0,1,0,0,1),nrow=1,ncol=10)
The matrix A could look something like this:
A=matrix(c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10),nrow=2,ncol=10)
I then want to swap the columns in A conditional on the vector V. If there is a 1 at an even column number (called r) in V, I want to swap the corresponding column r in A with column r-1 in A.
In the example above there is a 1 in column 2 and 10 in V, so I want to swap column 1 with column 2 and column 9 with column 10, so the matrix should look like this:
A=matrix(c(2,2,1,1,3,3,4,4,5,5,6,6,7,7,8,8,10,10,9,9),nrow=2,ncol=10)
Thanks
Upvotes: 1
Views: 58
Reputation: 52637
I can reproduce your desired result with:
V2 <- V * ((1:ncol(V) - 1) %% 2) # only preserve 1s at even spots
A[, 1:ncol(V2) - V2 + cbind(V2[, -1, drop=F], 0)]
which leads to:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 2 1 3 4 5 6 7 8 10 9
[2,] 2 1 3 4 5 6 7 8 10 9
We construct a vector to index the columns in A
such that they are re-ordered as per your spec. Start with 1:ncol(V)
, subtract V
from that to move the tagged columns back one column, and then shift V
by one column and add that back to move the columns before the tagged columns over by one.
Upvotes: 1