1

I have a table made with the knitr::kable function in R markdown. I want to make the order of the table go in descending number order based off one of the columns. Any suggestions?

lbevs
  • 11
  • 1
  • 3

2 Answers2

1

Can you please provide more details (is your output pdf or html?; do you absolutely need to use kable; etc.) and a reprex?

For html output:

You can try datatable() from package DT.

---
title: "Document title"
output: html_document
---

```{r}
# install in case you don't have it
# install.packages("DT")

# import DT
library(DT)

# example: order mtcars by descending column 2, which is 'cyl'
datatable(mtcars, options = list(order = list(2, "desc")))
```  

There's a list of available options here


For pdf output:

One strategy is to first order the data and then print the table using knitr::kable()

---
title: "Document title"
output: pdf_document
---

```{r}
# import libraries
library(knitr) # to print the table
library(dplyr) # to sort the data

# example: order mtcars by descending columns 2 and 3
mtcars_sorted <- mtcars[order(-mtcars[, 2], -mtcars[, 3]), ]    # (1)
mtcars_sorted <- mtcars %>% arrange(desc(cyl), desc(disp))      # (2)
mtcars_sorted <- mtcars %>% arrange(desc(.[[2]]), desc(.[[3]])) # (3)

# print the table using kable()
kable(mtcars_sorted, "latex")
```

enter image description here

Note that (1), (2) and (3) are all equivalents in the sense that all return the data in the desired order.

  • Option (1) uses base R; there's no need for dplyr here. Note the use of - inside of order() to denote descending. More details here

  • Options (2) and (3) use dplyr::arrange(). The former references column by names, while the later references them by index. More details here

Finally, if you want to improve how the printed table looks like, I recommend {kableExtra}

canovasjm
  • 501
  • 1
  • 3
  • 11
  • I am making it a PDF and I have to use the knitr::Kable function. I am trying to make it go in descending numerical order by the second third column – lbevs Feb 20 '21 at 00:25
0
---
title: "Kable table order"
output: html_document
---


```{r}
library(kableExtra)
mtcars2 <- mtcars[order(mtcars$mpg, decreasing = TRUE),] 
kable(mtcars2,format = "html")
```

enter image description here

There is probably even a way to do it inside kable(). Just change "decreasing = FALSE" for the opposite order.

Daniel_j_iii
  • 3,041
  • 2
  • 11
  • 27