Search code examples
rsorting

How to sort from smallest to largest the first row and the first column of a table in R


In the attached table I want to reorder from lowest to highest the values of the variable X and those of the variable Y, that is to say, that the variable X appears like this: 3,5,9 and 10 and Y:3,5,8 and 10.

These are the codes, with which I have generated the table, called "public":enter image description here

lim <- sample(2:10, 4)

lim1 <- sample(3:10, 4)

create_table <- function() {
  n_a <- sample(10:25,1)
  n_b <- 30-n_a
  n_c <- sample(5:18,1)
  n_d <- 20-n_c
  P3 <- rmultinom(1, n_a, prob=c(0.2, 0.4, 0.3, 0.1))
  P4 <- rmultinom(1, n_b, prob=c(0.1, 0.2, 0.4, 0.3))
  P5 <- rmultinom(1, n_a, prob=c(0.2, 0.4, 0.3, 0.1))
  P6 <- rmultinom(1, n_b, prob=c(0.1, 0.2, 0.4, 0.3))
  matrix(c(P3, P4, P5, P6), nrow = 4, ncol = 4,
          dimnames = list(c(lim[1], lim[2] ,lim[3],lim[4]),
           c(lim1[1] ,lim1[2], lim1[3], lim1[4])))
}

public <- create_table()

enter image description here


Solution

  • Use the following code:

    library(stringr)
    do.call('[', c(list(public), 
                      lapply(dimnames(public), str_sort, numeric = TRUE)))
      6 7 8 10
    3 2 4 0  0
    5 7 2 8  8
    6 3 2 3  3
    8 1 5 6  6
    

    This code could be written as:

    public[str_sort(rownames(public), numeric = TRUE), 
           str_sort(colnames(public), numeric = TRUE)]
    

    public[order(as.numeric(rownames(public))), order(as.numeric(colnames(public)))]
      6 7 8 10
    3 2 4 0  0
    5 7 2 8  8
    6 3 2 3  3
    8 1 5 6  6