Search code examples
rarraysswap

swap the columns of multidimensional array in R


I would like to swap the values of the 2nd and 3rd columns of the following array.

dat1=structure(1:18, .Dim = c(2L, 3L, 3L))
    
    
    > dat1
        , , 1
        
             [,1] [,2] [,3]
        [1,]    1    3    5
        [2,]    2    4    6
        
        , , 2
        
             [,1] [,2] [,3]
        [1,]    7    9   11
        [2,]    8   10   12
        
        , , 3
        
             [,1] [,2] [,3]
        [1,]   13   15   17
        [2,]   14   16   18

2nd column is in the 3rd position and the 3rd column is the 2nd position. Any help is appreciated.


Solution

  • You can specify the indexes you want to swap. For example

    dat1[,3:2,]<- dat1[,2:3,]
    

    Here you have a multidimensional array. Do when you specify dat1[x,y,z] then x values will be the visible rows, the y would be the visible columns, and z is which of the tables you want to manipulate. You can select one or more of these values for each of these dimensions. So dat1[,2:3,] selects the 2nd and 3rd column from all rows and tables (the blank parameters mean "all").