Order data.frame

Hi guys!

Fairly simple short question I guess, but I can't figure it out.

I want to order my dataframe, for my automatic forecast script.

It looks like this:

> best
#   KPI Best_method       Value
#1  MAE       Naive 1091.666667
#2 MASE       Naive    1.194195
#3 MAPE        addf   19.158691
#4 RMSE        addf 1326.316080

but i want, regardless of what values ​​are in the data frame:

> best
#   KPI Best_method       Value
#1 MAPE        addf   19.158691
#2 RMSE        addf 1326.316080
#3  MAE       Naive 1091.666667
#4 MASE       Naive    1.194195

This sequence of KPIs must be used as standard.
MAPE, RMSE, MAE, MASE

Thanks!

You could turn KPI into a factor variable specifying levels in the desired sequence and use that to order the observations.

library(dplyr, warn.conflicts = FALSE)
#> Warning: package 'dplyr' was built under R version 4.0.4

best <- tribble(
  ~KPI, ~Best_method, ~Value,
  "MAE", "Naive", 1091.666667,
  "MASE", "Naive", 1.194195,
  "MAPE", "addf", 19.158691,
  "RMSE", "addf", 1326.316080
)

best %>%
  mutate(KPI = factor(KPI, levels = c("MAPE", "RMSE", "MAE", "MASE"))) %>%
  arrange(KPI)
#> # A tibble: 4 x 3
#>   KPI   Best_method   Value
#>   <fct> <chr>         <dbl>
#> 1 MAPE  addf          19.2 
#> 2 RMSE  addf        1326.  
#> 3 MAE   Naive       1092.  
#> 4 MASE  Naive          1.19

Created on 2021-03-18 by the reprex package (v1.0.0)

3 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.