forcats

repository·main·Indexed 20 days ago

https://github.com/tidyverse/forcats

A tidyverse package for working with R factors. It provides tools for reordering, collapsing, and manipulating categorical variables, including functions like fct_reorder(), fct_infreq(), fct_relevel(), and fct_lump().

Tokens
512
Snippets
2
Records
3
Agent score
19%

What's inside forcats

  1. Overview of forcats for factor manipulation

    main

    In R, factors are used to handle categorical variables (variables with a fixed, known set of possible values). The forcats package provides tools to solve common problems with factors, such as changing the order of levels or the values themselves.

    Key capabilities include:

    • Reordering by another variable: Use fct_reorder().
    • Reordering by frequency: Use fct_infreq().
    • Manual reordering: Use fct_relevel() to change the order of levels by hand.
    • Collapsing levels: Use fct_lump() to collapse the least or most frequent values into an "other" category.
  2. Get started with forcats

    main

    To use forcats, load it using library(forcats) or as part of the tidyverse using library(tidyverse).

    Common workflows involve using forcats functions within dplyr::mutate() to transform factor columns before plotting with ggplot2 or performing counts.

    library(forcats)
    library(dplyr)
    library(ggplot2)
    
    # Example: Collapsing infrequent species into 'Other'
    starwars |> 
      filter(!is.na(species)) |> 
      mutate(species = fct_lump(species, n = 3)) |> 
      count(species)
    
    # Example: Reordering eye color by frequency for a plot
    starwars |> 
      mutate(eye_color = fct_infreq(eye_color)) |> 
      ggplot(aes(x = eye_color)) + 
      geom_bar() + 
      coord_flip()
  3. Install forcats

    main

    You can install forcats via CRAN or the development version from GitHub.

    To install the entire tidyverse suite:

    install.packages("tidyverse")

    To install only forcats:

    install.packages("forcats")

    To install the development version from GitHub using pak:

    # install.packages("pak")
    pak::pak("tidyverse/forcats")
    install.packages("forcats")