Search code examples
rdataframesorting

Sort from smallest to largest the first column of a table in R with data frame


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

These are the codes, with which I have generated the table, called "dataP":

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()

r <- sample(1:4,1)

dataP <- data.frame(c(lim1[1], lim1[2], lim1[3], lim1[4], "Suma"), 
            c(public[r,1], public[r,2], public[r,3], public[r,4],public[r,1]+ public[r,2]+ public[r,3]+public[r,4]))

colnames (dataP) <-lapply(list( "Y\\X={states[[1]][r]}","n[i/j == paste( {ansord})]" ),glue)

enter image description here

And the code is:

dataP[order(suppressWarnings(as.numeric(dataP$`X\\Y=`)), na.last = TRUE),]

Solution

  • If you have the ability, I suggest sorting it before you choose to drop the numbers in your first column and convert to strings.

    dataP <- data.frame("Y\\X=8" = c(9,8,6,10), "n[i/j==3]" = c(6,3,6,3), check.names=FALSE)
    dataP <- dataP[order(dataP$`Y\\X=8`),]
    rbind(dataP, data.frame("Y\\X=8"="Suma", "n[i/j==3]"=18, check.names=FALSE))
    #    Y\\X=8 n[i/j==3]
    # 3       6         6
    # 2       8         3
    # 1       9         6
    # 4      10         3
    # 11   Suma        18
    

    If, however, you cannot go back and fix the process, you can heal it by reconverting them back to numbers temporarily and then sorting based on them.

    dataP <- data.frame("Y\\X=8" = c(9,8,6,10,"Suma"), "n[i/j==3]" = c(6,3,6,3,18), check.names=FALSE)
    dataP[order(suppressWarnings(as.numeric(dataP$`Y\\X=8`)), na.last = TRUE),]
    #   Y\\X=8 n[i/j==3]
    # 3      6         6
    # 2      8         3
    # 1      9         6
    # 4     10         3
    # 5   Suma        18