0

I have a dataframe with below:

> df <- data.frame(BRANCH = c('AMB','GBM','CBE','GGN','KKE','KLM'), 
+                     OCT_REV = rnorm(6,50,5), 
+                     NOV_REV = rnorm(6,60,4), 
+                     DEC_REV = rnorm(6,55,10))
> df
  BRANCH  OCT_REV  NOV_REV  DEC_REV
1    AMB 57.76785 63.13167 39.21492
2    GBM 54.55668 64.89956 64.03446
3    CBE 50.61963 57.14174 54.64337
4    GGN 46.37132 65.48663 51.47701
5    KKE 49.24153 56.42736 46.68634
6    KLM 41.56488 63.67613 41.90277
> 

My actual DF has multiple columns and 16 Branches. But in the final report, Branches are ordered based on their location criteria. For example, I need to re-order the entire dataframe based on vector

Branches = c('AMB','GBM','GGN','CBE','KLM','KKE')

Expected Output

Branch  OCT_REV  NOV_REV  DEC_REV
   AMB 57.76785 63.13167 39.2149
   GBM 54.55668 64.89956 64.03446
   GGN 46.37132 65.48663 51.47701
   CBE 50.61963 57.14174 54.64337
   KLM 41.56488 63.67613 41.90277
   KKE 49.24153 56.42736 46.68634

For a single vector, I can use "match" function in R, but how to reorder entire dataframe based on another vector.

Karthik S
  • 11,348
  • 2
  • 11
  • 25
  • What do you mean by reorder entire dataframe? Wouldn't `match` suffice here? `df[match(df$BRANCH, Branches), ]` ? – Ronak Shah Jan 10 '20 at 05:26
  • `df$BRANCH <- forcats::fct_relevel(df$BRANCH, Branches); dplyr::arrange(df, BRANCH)` – Phil Jan 10 '20 at 05:29

1 Answers1

2

You can order your df using dplyr

library(dplyr)
df %>%
  arrange(factor(BRANCH, levels = Branches))