0

I use R package nycflights13 and made a table in this way.

rk <- rank(-tab.0); rk 
carrier.top10 <- names(tab.0)[rk<=10]
flights.1 <- subset(flights, carrier %in% carrier.top10)
flights.1$badflight <- as.factor(flights.1$dep_delay >= 60)
levels(flights.1$badflight) <- c("good", "bad")
tab.2 <- with(flights.1, table(carrier, badflight))
tab.2m <- addmargins(tab.2)
2*prop.table(tab.2m, 1)

    badflight
carrier       good        bad        Sum
    9E  0.88567983 0.11432017 1.00000000
    AA  0.93662169 0.06337831 1.00000000
    B6  0.91406524 0.08593476 1.00000000
    DL  0.94348946 0.05651054 1.00000000
    EV  0.86400810 0.13599190 1.00000000
    MQ  0.91904781 0.08095219 1.00000000
    UA  0.93275151 0.06724849 1.00000000
    US  0.96080109 0.03919891 1.00000000
    VX  0.92886377 0.07113623 1.00000000
    WN  0.91028718 0.08971282 1.00000000
    Sum 0.91787917 0.08212083 1.00000000

Now, I wanna sort this file with decreasing order in "good" part. What can I do?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Hello @hyeonny, in order to get more help, please provide a reproducible example as specified [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – larsoevlisen Nov 13 '19 at 08:57

2 Answers2

1

When you do prop.table you do not get a normal data.frame or matrix. You need to convert it into one and then use order. Try

data <- 2*prop.table(tab.2m, 1)
temp <- as.data.frame.matrix(data)
temp[order(temp$good, decreasing = TRUE), ]

Tried it on this example using mtcars

data <- prop.table(with(mtcars, table(cyl, am)), 1)
temp <- as.data.frame.matrix(data)
temp[order(temp$`0`, decreasing = TRUE), ]

#          0         1
#8 0.8571429 0.1428571
#6 0.5714286 0.4285714
#4 0.2727273 0.7272727
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

Sorting by column is usually done by using order/sort:

mtcars[order(mtcars$mpg), ]
Hart Radev
  • 361
  • 1
  • 10