anderwyang
anderwyang

Reputation: 2411

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))

Upvotes: 1

Views: 185

Answers (3)

s_baldur
s_baldur

Reputation: 33498

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"

Upvotes: 1

Arshiya
Arshiya

Reputation: 103

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))

Upvotes: 0

Migwell
Migwell

Reputation: 20107

> 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.

Upvotes: 1

Related Questions