0

in my desired output, the result for red would be printed before the result for green. Specifically, how to a change the order of factor levels for printing in a kable (or similar) table?

var1<-sample(c("red", "green"), 100, replace=T)
var2<-rnorm(100)
df<-data.frame(var1, var2)

library(tidyverse)
library(knitr)
df %>% 
  group_by(var1) %>% 
  summarize(avg=mean(var2)) %>% 
  mutate(var1=fct_relevel(var1, "red", "green")) %>% 
  kable()
spindoctor
  • 1,719
  • 1
  • 18
  • 42
  • 1
    `...arrange(match(c('red', 'green'), var1)) %>%...` ? See this post https://stackoverflow.com/questions/11977102/order-data-frame-rows-according-to-vector-with-specific-order – Ronak Shah Jun 12 '21 at 10:47
  • This looks good, but this all seems unwieldy, no? – spindoctor Jun 12 '21 at 10:58

1 Answers1

0

Simply use arrange to sort your dataframe by your var1

var1<-sample(c("red", "green"), 100, replace=T)
var2<-rnorm(100)
df<-data.frame(var1, var2)

library(tidyverse)
library(knitr)
df %>% 
  group_by(var1) %>% 
  summarize(avg=mean(var2)) %>% 
  mutate(var1=fct_relevel(var1, "red", "green")) %>% 
  arrange(var1) %>% # Arranges the data frame by this variable
  kable()

|var1  |        avg|
|:-----|----------:|
|red   |  0.0999524|
|green | -0.0378017|

mhovd
  • 3,724
  • 2
  • 21
  • 47
  • This won't work as there is my specific case requires ordering the factor levels by some non-numeric quantity. This seems like a limitation of kable. – spindoctor Jun 12 '21 at 10:52
  • In that case you are better served with the answer provided in the question linked by @Ronak Shah – mhovd Jun 12 '21 at 10:58
  • 1
    No, this will work, actually. The arrange() function actually orders the data frame in the order of the factor levels set in the `mutate(fct_relevel)` command. It works just great. I prefer this answer because it is wholly based in the `tidyverse` Thank you. – spindoctor Jun 14 '21 at 14:54