rdataframedplyrforcats

How to relevel a factor inside a tibble


I am trying to change the levels of a factor field, Grade, in the following tibble:

# A tibble: 10 x 8
      id destination package_type  `7_day_price` `14_day_price` for_families for_groups Grade
   <dbl> <chr>       <chr>                 <dbl>          <dbl>        <dbl>      <dbl> <fct>
 1     1 Aruba       all inclusive          1200           2000            1          1 A    
 2     2 Bora bora   flight only            1400           2333            1          0 B    
 3     3 Wales       flight only             125            210            1          1 D    
 4     4 Cancun      flight only            1600           2750            1          1 B    
 5     5 Antigua     all inclusive          2100           3500            0          1 A    
 6     6 Mustique    half board             7599          12670            0          0 A    
 7     7 Tobago      half board             2459           4010            1          1 B    
 8     8 Jamaica     all inclusive          1850           3090            0          1 C    
 9     9 St Lucia    all inclusive          1800           3000            1          0 B    
10    10 Guadeloupe  all inclusive          1750           2900            1          1 C   

I am doing this with the code:

library(tidyverse)
df %>% fct_relevel(df['Grade'],"A","B","C","D")

but this is returning the error:

Error: f must be a factor (or character vector or numeric vector).

This field IS a factor, what am I doing wrong?


Solution

  • Try to relevel inside mutate:

    df %>%
      mutate(Grade = fct_relevel(Grade, "A","B","C","D"))
    

    Here is a simple toy example:

    df <- tibble(Grade = factor(LETTERS[1:4]))
    
    pull(df, Grade) %>% levels()
    [1] "A" "B" "C" "D"
    
    df %>% mutate(Grade = fct_relevel(Grade, "B", "C", "A", "D")) %>% pull(Grade) %>% levels()
    [1] "B" "C" "A" "D"
    

    To reorder your tibble using the releveled factor, use dplyr::arrange.

    df %>% mutate(Grade = fct_relevel(Grade, "B", "C", "A", "D")) %>% arrange(Grade)