Learn R Programming

fctutils (version 0.0.7)

ft_reorder_within: Reorder Factor Levels Within Groups

Description

Reorders the levels of a factor vector within groups defined by another factor vector.

Usage

ft_reorder_within(factor_vec, group_vec, by, fun = mean, decreasing = FALSE)

Value

A factor vector with levels reordered within groups.

Arguments

factor_vec

A factor vector to be reordered.

group_vec

A factor vector defining the groups.

by

A numeric vector to order by.

fun

A function to summarize within groups (e.g., mean, median).

decreasing

Logical. Should the ordering be decreasing? Default is FALSE.

Author

Kai Guo

Examples

Run this code
# Example data
data <- data.frame(
  item = factor(c('A', 'B', 'C', 'D', 'E', 'F')),
  group = factor(c('G1', 'G1', 'G1', 'G2', 'G2', 'G2')),
  value = c(10, 15, 5, 20, 25, 15)
)
data <- rbind(data, data)
# Reorder 'item' within 'group' by 'value'
data$item <- ft_reorder_within(data$item, data$group, data$value, mean)

Run the code above in your browser using DataLab