2.4 C
London
Friday, December 20, 2024
HomeStatistics TutorialRHow to Reorder Factor Levels in R (With Examples)

How to Reorder Factor Levels in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

Occasionally you may want to re-order the levels of some factor variable in R. Fortunately this is easy to do using the following syntax:

factor_variable factor(factor_variable, levels=c('this', 'that', 'those', ...))

The following example show how to use this function in practice.

Example: Reorder Factor Levels in R

First, let’s create a data frame with one factor variable and one numeric variable:

#create data frame
df frame(region=factor(c('A', 'B', 'C', 'D', 'E')),
                 sales=c(12, 18, 21, 14, 34))

#view data frame
df

  region sales
1      A    12
2      B    18
3      C    21
4      D    14
5      E    34

We can use the levels() argument to get the current levels of the factor variable region:

#display factor levels for region
levels(df$region)

[1] "A" "B" "C" "D" "E"

And we can use the following syntax to re-order the factor levels:

#re-order factor levels for region
df$region factor(df$region, levels=c('A', 'E', 'D', 'C', 'B'))

#display factor levels for region
levels(df$region)

[1] "A" "E" "D" "C" "B"

The factor levels are now in the order that we specified using the levels argument.

If we then want to create a barplot in R and order the bars based on the factor levels of region, we can use the following syntax:

#re-order data frame based on factor levels for region
df order(levels(df$region)),]

#create barplot and place bars in order based on factor levels for region
barplot(df$sales, names=df$region)

Reorder factor levels for barplot in R

Notice how the bars are in the order of the factor levels that we specified for region.


You can find more R tutorials on this page.

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories