-2

i would like to move columns in a matrix by one to the right.

Input <- data.frame(read.csv2 ....)

The matrix looks like:

1   2   3   4
1   2   3   4 
1   2   3   4 

and should be like:

4   1   2   3
4   1   2   3 
4   1   2   3

I googled it but i couldn't find anything.

thanks for your help!!!

This looks like pretty good Moving columns within a data.frame() without retyping

Community
  • 1
  • 1
meck373
  • 1,114
  • 1
  • 18
  • 31

1 Answers1

1

Although the answer in comments works for a one-column shift to the right, its fiddly to extend that approach to other shifts and directions.

It boils down to generating the vector of the order of columns that you want to return, and then subsetting columns.

So your original Q boils down to generating c(4,1,2,3). There's a handy function in the magic package that can do this:

> install.packages("magic") # if you dont have it
> magic::shift(1:4,1)
[1] 4 1 2 3

So:

> Data[,magic::shift(1:ncol(Data),1)]
     [,1] [,2] [,3] [,4]
[1,]   13    1    5    9
[2,]   14    2    6   10
[3,]   15    3    7   11
[4,]   16    4    8   12

answers your original question. This is then easy to extend to shifts by more than one, or negative (leftward) shifts:

> Data[,magic::shift(1:ncol(Data),-2)]
     [,1] [,2] [,3] [,4]
[1,]    9   13    1    5
[2,]   10   14    2    6
[3,]   11   15    3    7
[4,]   12   16    4    8

Of course the right way is now to create matrix shift function:

> mshift = function(m,n=1){m[,magic::shift(1:ncol(m),n)]}

which you can check:

> mshift(Data,1)
     [,1] [,2] [,3] [,4]
[1,]   13    1    5    9
[2,]   14    2    6   10
[3,]   15    3    7   11
[4,]   16    4    8   12
Spacedman
  • 92,590
  • 12
  • 140
  • 224