Change row order in a matrix/dataframe

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

    Encounter this problem today and here I am providing another solution for your interests.

    m <- matrix(1:9, ncol=3, byrow=TRUE)    
    apply(m,2,rev)
    
    0 讨论(0)
  • 2020-11-30 03:46

    I would reverse the rows an index starting with the number of rows, along this line

    revdata <-  thedata[dim(thedata)[1L]:1,]
    
    0 讨论(0)
  • 2020-11-30 03:48

    Veeery late, but this seems to be working fast, does not need any extra packages and is simple:

    for(i in 1:ncol(matrix)) {matrix[,i] = rev(matrix[,i])}
    

    I guess that for frequent use, one would make a function out of it. Tested with R v=3.3.1.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-30 04:03

    You can reverse the order of a data.frame using the dplyr package:

    iris %>% arrange(-row_number())
    

    Or without using the pipe-operator by doing

    arrange(iris, -row_number())
    
    0 讨论(0)
  • 2020-11-30 04:05

    I think this is the simplest way:

    MyMatrix = matrix(1:20, ncol = 2)
    MyMatrix[ nrow(MyMatrix):1, ]
    

    If you want to reverse the columns, just do

    MyMatrix[ , ncol(MyMatrix):1 ]
    
    0 讨论(0)
提交回复
热议问题