更改因子水平并重新排列数据框

Change factor levels and rearrange dataframe

这里是使用 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')
      )

我想使用 forcats 重新排列我的因子顺序,以便数据框根据以下顺序重新排序,这样条形图也将显示如下:

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

但这留下了以下内容:

# 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
  

对不起,我总是对fct_relevelfct_recode

感到困惑

这个错误很容易犯。您必须将列向量提供给 fct_relevel。像这样:


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

reprex package (v0.3.0)

于 2021 年 1 月 11 日创建