Change row order in a matrix/dataframe

前端 未结 7 862
盖世英雄少女心
盖世英雄少女心 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 03:58

    We can reverse the order of row.names (for data.frame only):

    # create data.frame
    m <- matrix(1:9, ncol=3, byrow=TRUE)
    df_m <- data.frame(m)
    
    #reverse
    df_m[rev(rownames(df_m)), ]
    
    #   X1 X2 X3
    # 3  7  8  9
    # 2  4  5  6
    # 1  1  2  3
    

提交回复
热议问题