Search code examples
r

Order every tables the same way


I would like to order several tables by rowname with the same order of rowname, based for example on a vector.

My problem is that I don't want to order alphabetically, but rather with a specific order.

Also, every table do not have the same size nor rownames, but still, they should follow the same order with their remaining rownames.

Reproducible example

### Initiating data
# Complete table with unordered rownames
tabComplete <- data.frame(Group=c("E", "A", "D", "B", "C"),
                          Values=c("order", "This", "correct", "is", "the"), 
                          row.names=c("Fifth", "First", "Fourth", "Second", "Third"))

           Group Values
Fifth      E order
First      A This
Fourth     D correct
Second     B is
Third      C the

# Two tables that I would like to order by rownames
tabPortion1 <- tabComplete[c(1, 3, 5), ]
tabPortion2 <- tabComplete[c(1, 2, 4), ]
    
       Group  Values
Fifth      E   order
Fourth     D correct
Third      C     the
    
       Group Values
Fifth      E  order
First      A   This
Second     B     is

What I would like to achieve

# Based on a vector, I would like that every table follow the same order but the have different sizes
vecMyOrder <- c("First", "Second", "Third", "Fourth", "Fifth")

# Tables with the correct order
tabComplete[c("First", "Second", "Third", "Fourth", "Fifth"), ]
tabPortion1[c("Third", "Fourth", "Fifth"), ]
tabPortion2[c("First", "Second", "Fifth"), ]

       Group  Values
First      A    This
Second     B      is
Third      C     the
Fourth     D correct
Fifth      E   order

       Group  Values
Third      C     the
Fourth     D correct
Fifth      E   order

       Group Values
First      A   This
Second     B     is
Fifth      E  order

Thank you


Solution

  • Given a list of dataframes lst <- list(tabComplete, tabPortion1, tabPortion2), you can try this

    lapply(
        lst,
        \(x) x[order(match(row.names(x), vecMyOrder)), ]
    )
    

    or

    lapply(
        lst,
        \(x) x[order(factor(row.names(x), levels = vecMyOrder)), ]
    )
    

    which gives

    [[1]]
           Group  Values
    First      A    This
    Second     B      is
    Third      C     the
    Fourth     D correct
    Fifth      E   order
    
    [[2]]
           Group  Values
    Third      C     the
    Fourth     D correct
    Fifth      E   order
    
    [[3]]
           Group Values
    First      A   This
    Second     B     is
    Fifth      E  order