Search code examples
rforcats

In R , a question about change variable type to 'factor'


I use the code below to change the variable 'period' from 'character' to 'factor' (and factor levels sequence to match the order contained in 'period' text).

Below is the current code. Is there an available function for it ?

library(tidyverse)

raw_data <- 
  data.frame(
    period=c('Q2','Q1','8','7','40','41'),
    amount=c(1:6)
  ) 


arranged_data <- raw_data %>% arrange(match(parse_number(period),c(1:41))) %>% 
  mutate(period=fct_inorder(period))

Solution

  • lvls <- unique(raw_data$period)
    raw_data$period <- factor(raw_data$period, levels = lvls[order(parse_number(lvls))])
    

    Resulting in:

    levels(raw_data$period )
    [1] "Q1" "Q2" "7"  "8"  "40" "41"