Learn/R Programming/Data Manipulation

Forcats for Factors

Topic: forcats

Advertisement

Introduction

The forcats package provides tools for working with factors. It makes factor handling intuitive.

Creating Factors

library(forcats)

# Simple factor
f <- factor(c("a", "b", "a", "c"))

# With fct() functions
f <- fct(c("a", "b", "a", "c"))

Factor Level Manipulation

f <- factor(c("a", "b", "a", "c"))

# Reorder levels
fct_reorder(f, .x = c(1, 2, 1, 3))

# Lump levels together
fct_lump(f, n = 2)

# Collapse levels
fct_collapse(f, "new" = c("a", "b"))

# Rename levels
fct_recode(f, "A" = "a", "B" = "b")

Factor Order

f <- factor(c("low", "medium", "high"))

# Reorder by frequency
fct_infreq(f)

# Reorder by appearance
fct_inorder(f)

# Manual reorder
fct_relevel(f, "low", "medium", "high")

Summary

forcats makes factor manipulation easy. Use these functions for categorical data handling.

Advertisement

Advertisement

Need More Practice?

Get personalized R programming help from ChatWhole's AI-powered platform.

Get Expert Help →