Arthur Carvalho Brito
Arthur Carvalho Brito

Reputation: 560

Change factor levels and rearrange dataframe

here is a sample data frame using dput:

 df <-
      structure(
        list(layer = structure(
          1:5,
          .Label = c(
            'CEOS and managers',
            'Clerks and services',
            'Production',
            'Professionals',
            'Technicians'
          ),
          class = 'factor'
        )),
        row.names = c(NA,-5L),
        class = c('tbl_df', 'tbl', 'data.frame')
      )

I want to rearrange my factor orders using forcats so that the data frame is reordered according to the order below, so that bar charts would also be displayed as such:

df %>%
  mutate(
    layer = forcats::fct_relevel(
      'CEOs and managers',
      'Professionals',
      'Technicians',
      'Clerks and services',
      'Production')
  ) %>%
  arrange(layer)

But this leaves the following:

# A tibble: 5 x 1
  layer            
  <fct>            
1 CEOs and managers
2 CEOs and managers
3 CEOs and managers
4 CEOs and managers
5 CEOs and managers
  

Sorry, I am always so confused with fct_relevel and fct_recode

Upvotes: 1

Views: 289

Answers (1)

Magnus Nordmo
Magnus Nordmo

Reputation: 951

This mistakes is easy to make. You have to supply the column vector to fct_relevel. Like so:


library(dplyr,warn.conflicts = F)
library(forcats)

df <-
  structure(
    list(layer = structure(
      1:5,
      .Label = c(
        'CEOS and managers',
        'Clerks and services',
        'Production',
        'Professionals',
        'Technicians'
      ),
      class = 'factor'
    )),
    row.names = c(NA,-5L),
    class = c('tbl_df', 'tbl', 'data.frame')
  )

df %>%
  mutate(layer = forcats::fct_relevel(
    layer,c(
      'CEOS and managers',
      'Professionals',
      'Technicians',
      'Clerks and services',
      'Production'))) %>% 
  arrange(layer)
#> # A tibble: 5 x 1
#>   layer              
#>   <fct>              
#> 1 CEOS and managers  
#> 2 Professionals      
#> 3 Technicians        
#> 4 Clerks and services
#> 5 Production

Created on 2021-01-11 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions