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

Viewed 71

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))
3 Answers
> raw_data %>% mutate(period = factor(period)) %>% as_tibble()
# A tibble: 6 × 2
  period amount
  <fct>   <int>
1 Q2          1
2 Q1          2
3 8           3
4 7           4
5 40          5
6 41          6

As you can see, you just have to call the factor() function on a vector to convert it into a factor.

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"

I believe this should work! The issue is that fct_inorder doesn't change column type, so you should turn the column into a factor first:

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 = as.factor(period)) %>%
   mutate(period=fct_inorder(period))
Related