Change row order in a matrix/dataframe

前端 未结 7 828
盖世英雄少女心
盖世英雄少女心 2020-11-30 03:15

I need to change/invert rows in my data frame, not transposing the data but moving the bottom row to the top and so on. If the data frame was:

1 2 3 
4 5 6
7         


        
相关标签:
7条回答
  • 2020-11-30 04:07

    There probably are more elegant ways, but this works:

    m <- matrix(1:9, ncol=3, byrow=TRUE)
    
    # m[rev(seq_len(nrow(m))), ]  # Initial answer
    m[nrow(m):1, ]
         [,1] [,2] [,3]
    [1,]    7    8    9
    [2,]    4    5    6
    [3,]    1    2    3
    

    This works because you are indexing the matrix with a reversed sequence of integers as the row index. nrow(m):1 results in 3 2 1.

    0 讨论(0)
提交回复
热议问题